今天,在一个项目中,我尝试使用正则表达式,并学习了有关组和如何使用它们的知识。我使用这站点来测试it.The问题,每当我编写以下regex时:
(?=\S*\d)
,这个站点给了我一个错误:the expression can match 0 characters and therefore can match infinitely.
虽然这不会引发任何错误:
(?=\S*\d)(S{6,16})
有人能向我解释一下这个错误的含义吗?
发布于 2015-06-28 06:36:52
因为“头”是断言,它们不消耗任何字符。
(?=\S*\d)这样编写正则表达式时,会检查是否包含零或多个非空格,后面跟着一个数字。但是regex引擎并没有使用这些字符。指针保持在相同的位置。
示例
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字符。https://stackoverflow.com/questions/31096855
复制相似问题