简体   繁体   English

正向超前无法按预期工作

[英]Positive lookahead not working as expected

I have the following regex with a positive lookahead: 我有以下正则表达式,具有积极的前瞻性:

/black(?=hand)[ s]/

I want it to match blackhands or blackhand . 我要它匹配黑手黑手 However, it doesn't match anything. 但是,它不匹配任何内容。 I am testing on Regex101 . 我正在Regex101上进行测试。

What am I doing wrong? 我究竟做错了什么?

Lookahead does not consume the string being searched. 前瞻不消耗正在搜索的字符串。 That means that the [ s] is trying to match a space or s immediately following black . 这意味着[ s]试图匹配紧接black的空格或s However, your lookahead says that hand must follow black , so the regular expression can never match anything. 但是,先行说明您的必须跟随black ,因此正则表达式永远无法匹配任何内容。

To match either blackhands or blackhand while using lookahead, move [ s] within the lookahead: black(?=hand[ s]) . 要在使用前瞻时匹配黑手黑手,请在前瞻中移动[ s]black(?=hand[ s]) Alternatively, don't use lookahead at all: blackhand[ s] . 另外,也不要完全使用前瞻性: blackhand[ s]

You regex isn't matching blackhands or blackhands because it is trying to match a space or letter s (character class [ s] ) right after text black and also looking ahead hand after black . 你正则表达式是不匹配blackhandsblackhands ,因为它试图匹配一个空格或字母s (字符类[ s]文本后右) black ,也展望未来hand后, black

To match both inputs you will need this lookahead: 为了匹配两个输入,您需要提前进行以下操作:

/black(?=hands?)/

Or just don't use any lookahead and use: 或者只是不使用任何先行方式并使用:

/blackhands?/

Good reference on lookarounds 关于环视的良好参考

In short, you should use 简而言之,您应该使用

/\bblackhands?\b/

Now, your regex is a bit too complex for this task. 现在,您的正则表达式对于此任务有点太复杂了。 It consists of 它包括

  • black - matching black literally black -从字面上匹配black
  • (?=hand) - a positive lookahead that requires hand to appear right after black - but does not consume characters, engine stays at the same position in string! (?=hand) -正向提前, 要求 handblack之后立即出现- 但不消耗字符,引擎停留在字符串中的相同位置!
  • [ s] - a character class matching either a space or a s - obligatorily right after the black . [ s] -一个字符类,它紧随black之后匹配一个空格或s

So, you will never get your matches, because a space or s do not appear in the first position of hand (it is h ). 因此,您永远不会获得匹配,因为空格或s不会出现在hand的第一个位置(它是h )。

This is how lookarounds work : 这是环顾四周的工作方式

The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match . 区别在于,环顾四周实际上是匹配字符,但随后放弃了匹配,仅返回结果:match或no match That is why they are called "assertions" . 这就是为什么它们被称为“断言”的原因 They do not consume characters in the string, but only assert whether a match is possible or not. 它们不使用字符串中的字符,而仅声明是否可以匹配。

In your case, it is not necessary. 在您的情况下,则没有必要。 Just use \\b - a word boundary - to match whole words blackhand or blackhands . 只需使用\\b单词边界 )即可匹配整个单词blackhandblackhands

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM