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?
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?
In short, you should use
Now, your regex is a bit too complex for this task. It consists of
black
- matchingblack
literally(?=hand)
- a positive lookahead that requireshand
to 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 ofhand
(it ish
).This is how lookarounds work:
In your case, it is not necessary. Just use
\b
- a word boundary - to match whole wordsblackhand
orblackhands
.You regex isn't matching
blackhands
orblackhands
because it is trying to match a space or letters
(character class[ s]
) right after textblack
and also looking aheadhand
afterblack
.To match both inputs you will need this lookahead:
Or just don't use any lookahead and use:
Good reference on lookarounds
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]
.