Reputation: 749
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?
Upvotes: 4
Views: 5378
Reputation: 626835
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
.
Upvotes: 1
Reputation: 785146
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?/
Upvotes: 4
Reputation: 1377
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]
.
Upvotes: 8