A positive outlook doesn't work well

I have the following regex with a positive lookahead:

/black(?=hand)[ s]/

      

I want it to match black or black hands . However, that doesn't mean anything. I am testing Regex101 .

What am I doing wrong?

+3


source to share


3 answers


Lookahead does not use string search. This means it is [ s]

trying to match a space or s just after black . However, your view is that the hand has to follow black , so the regex will never be able to match anything.



For comparison, black or dark minions using lookahead, move [ s]

in lookahead: black(?=hand[ s])

. In addition, do not use lookahead general: blackhand[ s]

.

+4


source


Regex does not match blackhands

or blackhands

because it tries to match a space or letter s

(class character [ s]

) immediately after the text black

, and also look ahead hand

after black

.

To combine both inputs, you need this view:

/black(?=hands?)/

      



Or just don't use any view and use:

/blackhands?/

      

Good link to search terms

+3


source


In short, you should use

/\bblackhands?\b/

      

Now your regex is too complex for this task. It consists of

  • black

    - black

    literal match
  • (?=hand)

    - positive result, which requires hand

    to appear immediately after black

    - , but does not consume characters, the engine remains in one position in the line!
  • [ s]

    - a character class that matches either a space or s

    is mandatory afterblack

    .

So, you will never get your matches because the space or s

does not appear in the first position hand

(this h

).

This is how search queries work :

The difference is that lookaround actually matches characters, but then gives a match, returning only the result: match or no match . This is why they are called "statements". They do not consume characters in the string, but only assert if a match is possible.

This is optional in your case. Just use \b

- a word border - to match whole words blackhand

or blackhands

.

+1


source







All Articles