【问题标题】:Regex Look Ahead正则表达式向前看
【发布时间】:2015-06-28 06:34:04
【问题描述】:

今天我在一个项目中尝试使用正则表达式并了解了组以及如何使用它们。我正在使用this 站点对其进行测试。问题是每当我编写以下正则表达式时:

(?=\S*\d)

,该网站给我一个错误:the expression can match 0 characters and therefore can match infinitely.

虽然这不会引发任何错误:

(?=\S*\d)(\S{6,16})

谁能给我解释一下错误的含义。

【问题讨论】:

    标签: regex lookahead


    【解决方案1】:

    因为前瞻是断言,它们不消耗任何字符。

    (?=\S*\d)
    

    当您像这样编写正则表达式时,它检查它是否包含零个或多个非空格,后跟一个数字。但是正则表达式引擎不会使用这些字符。并且指针保持在相同的位置。

    示例

     hello123
    |
    This is the initial position of pointer. It the checking starts from here
    
    hello123
    |
    (?=\S*\d). Here it matches \S
    
    hello123
     |
     (?=\S*\d)
    
    This continues till
    
    hello123
           |
         (?=\S*\d) Now the assertion is matched. The pointer backtracks to the position from where it started looking for regex.
    
     hello123
    |
    Now you have no more pattern to match. For the second version of the regex, the matching then begins from this postion
    

    那么和

    有什么区别
    (?=\S*\d)(\S{6,16})
    

    这里,

    • (?=\S*\d) 这部分进行检查。我再重复一遍,这部分不消耗任何字符,它只是检查。

    • (\S{6,16})这部分做的是输入字符串中字符的消耗。也就是说,它至少消耗6 非空格字符和最大16 字符。

    【讨论】:

    • 哦,这解释了很多,我认为前瞻的工作是找到匹配项并停在找到匹配项的位置。所以这意味着断言不能单独使用,因为它们只执行检查并返回到起始位置。我们需要一个也消耗字符的正则表达式。
    • @JaymitDesai 你明白了。它的性能正如名字所暗示的那样。如果匹配发生,则向前看。看并不意味着占用:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    相关资源
    最近更新 更多