lollipop43
V2EX  ›  问与答

这个正则表达式有问题嘛?

  •  
  •   lollipop43 · Mar 3, 2021 · 1177 views
    This topic created in 1918 days ago, the information mentioned may be changed or developed.

    PAT 1108 这道题里有一个定义,合法的输入是: A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. 我写的表达式是这样的,有漏网之鱼嘛 (1000)|(-1000)|(-?\d{1,3}(.\d{0,2})?)

    2 replies    2021-03-03 23:57:07 +08:00
    noqwerty
        1
    noqwerty  
       Mar 3, 2021
    1. 小数点需要转义,用\.
    2. 应该要加上^$吧?不然 1001 里面的 100 也能被第三部分匹配到。
    3. 另外类似 001 这种数字也能被匹配到,不知道是否符合要求。
    imdong
        2
    imdong  
       Mar 3, 2021
    ^-?([1-9][0-9]{0,2})?[0-9]$

    这样应该更好一些,至于 -0 的问题,如果要解决,就复制成两段.

    ^([1-9][0-9]{0,2})?[0-9]|-([1-9][0-9]{0,3})$
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5837 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 02:02 · PVG 10:02 · LAX 19:02 · JFK 22:02
    ♥ Do have faith in what you're doing.