Avoid matches with given text in fixed position

Viewed 56

I'm have two kinds of string (something could be any kind of text):

  • <<something>>
  • <<CODE:something>>

The patterns of the Regex used to find both are:

  • <<(.*?)>>
  • <<CODE:(.*?)>>

As you can see, there's an issue that the first pattern can also find the second string. Since both start with << and the first pattern is (.*?), it's possible get an unwanted match.

How can I prevent finding strings with CODE: while still inside << >>?

1 Answers

Use

<<(?!CODE:)(.*?)>>

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  <<                       '<<'
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    CODE:                    'CODE:'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  >>                       '>>'
Related