Positive lookahead not working as expected

2019-05-14 03:46发布

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.

What am I doing wrong?

3条回答
欢心
2楼-- · 2019-05-14 04:36

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
  • (?=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!
  • [ s] - a character class matching either a space or a s - obligatorily right after the black.

So, you will never get your matches, because a space or s do not appear in the first position of hand (it is 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. 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.

查看更多
闹够了就滚
3楼-- · 2019-05-14 04:38

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.

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

查看更多
仙女界的扛把子
4楼-- · 2019-05-14 04:45

Lookahead does not consume the string being searched. That means that the [ s] is trying to match a space or s immediately following black. However, your lookahead says that hand must follow black, so the regular expression can never match anything.

To match either blackhands or blackhand while using lookahead, move [ s] within the lookahead: black(?=hand[ s]). Alternatively, don't use lookahead at all: blackhand[ s].

查看更多
登录 后发表回答