问题
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?
回答1:
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].
回答2:
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
回答3:
In short, you should use
/\bblackhands?\b/
Now, your regex is a bit too complex for this task. It consists of
black- matchingblackliterally(?=hand)- a positive lookahead that requireshandto appear right afterblack- but does not consume characters, engine stays at the same position in string![ s]- a character class matching either a space or as- obligatorily right after theblack.
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.
来源:https://stackoverflow.com/questions/31347686/positive-lookahead-not-working-as-expected