首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex展望未来

Regex展望未来
EN

Stack Overflow用户
提问于 2015-06-28 06:34:04
回答 1查看 102关注 0票数 0

今天,在一个项目中,我尝试使用正则表达式,并学习了有关组和如何使用它们的知识。我使用站点来测试it.The问题,每当我编写以下regex时:

(?=\S*\d)

,这个站点给了我一个错误:the expression can match 0 characters and therefore can match infinitely.

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

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

有人能向我解释一下这个错误的含义吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-28 06:36:52

因为“头”是断言,它们不消耗任何字符。

代码语言:javascript
复制
(?=\S*\d)

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

示例

代码语言:javascript
复制
 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

所以有什么区别

代码语言:javascript
复制
(?=\S*\d)(\S{6,16})

这里,

  • (?=\S*\d)这部分做检查。我再说一遍,这个部分不消耗任何字符,它只是检查。
  • (\S{6,16})此部分负责输入字符串中字符的消耗。也就是说,它消耗了最小的6非空间字符和最大的16字符。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31096855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档