正则表达式向前看
Regex Look Ahead
今天我在一个项目中尝试使用正则表达式并学习了组以及如何使用它们。我正在使用 this 站点来测试 it.The 问题是每当我编写以下正则表达式时:
(?=\S*\d)
,该网站给我一个错误:the expression can match 0 characters and therefore can match infinitely.
虽然这不会引发任何错误:
(?=\S*\d)(\S{6,16})
任何人都可以向我解释错误的含义。
因为前瞻是断言,它们不消耗任何字符。
(?=\S*\d)
当你像这样写正则表达式时,它 检查 是否包含零个或多个非 space 后跟一个数字。但是这些字符不会被正则表达式引擎消耗。并且指针保持在同一位置。
例子
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
个非 space 个字符,最多 16
个字符。
今天我在一个项目中尝试使用正则表达式并学习了组以及如何使用它们。我正在使用 this 站点来测试 it.The 问题是每当我编写以下正则表达式时:
(?=\S*\d)
,该网站给我一个错误:the expression can match 0 characters and therefore can match infinitely.
虽然这不会引发任何错误:
(?=\S*\d)(\S{6,16})
任何人都可以向我解释错误的含义。
因为前瞻是断言,它们不消耗任何字符。
(?=\S*\d)
当你像这样写正则表达式时,它 检查 是否包含零个或多个非 space 后跟一个数字。但是这些字符不会被正则表达式引擎消耗。并且指针保持在同一位置。
例子
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
个非 space 个字符,最多16
个字符。