Regex multiple lookbehinds order

Viewed 135

I've got a regex that I want to use to match word characters after a - if there are not any proceeding word characters.

(?<!\w)(?<=-)\w+

For the string

I want -to match a word-if it has a '-' bofore it and only-if '-' is not preceded by a word character.

I would expect it to only match to. However, it actually matches to, if, and if.

Demo

If I take the positive lookbehind out

(?<!\w)-\w+

In the same string, it only matches -to as expected but I don't want the - in the match information.

Is it possible to chain positive and negative lookbehinds so they happen in order?

2 Answers

The pattern that you tried (?<!\w)(?<=-)\w+ makes 2 assertions the current position:

  • (?<!\w) is there not a word character directly to the left
  • (?<=-) is there a - directly to the left

This can also be written as just (?<=-)\w+ as the positive lookbehind asserts that the exact match should be at the left.

You get the matches to, if, and if because that assertion is true at multiple places.


You can use (?<=\W-) to assert what is directly to the left is a non word character \W followed by -

(?<=\W-)\w+

Regex demo

Use

(?<=\B-)\w+

See proof

Explanation

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    \B                       the boundary between two word chars (\w)
                             or two non-word chars (\W)
--------------------------------------------------------------------------------
    -                        '-'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                           more times (matching the most amount
                           possible))
Related