Search code examples
regex

Search for a Text Not Preceded by a Pattern with a Variable Number of Spaces


I want to match instances of like to match the Table.Field that are not preceed by the words and or where. However, there can be a variable number of spaces between these forbidden words and Table.Field.

The following regex represents what I would like to achieve, but it is invalid when using a PCRE engine because of the + quantifier and the alternation (and|where) inside the negative lookbehind:

(?<!(and|where) )Table\.Field

Must match

Table.Field
something Table.Field
 bTable.Field
Table.Field

Must not match

and Table.Field
where Table.Field
and       Table.Field
where  Table.Field

Thanks


Solution

  • You can use

    \b(?:and|where)\s+Table\.Field(*SKIP)(*F)|Table\.Field
    

    See the regex demo.

    Details:

    • \b(?:and|where)\s+Table\.Field(*SKIP)(*F) - a whole word and or where is matched, then one or more whitespaces (\s+), and then Table.Field string, and then this match is discarded and the new search is made from the position right after this matched text
    • | - or
    • Table\.Field - Table.Field string.

    See How do (*SKIP) or (*F) work on regex? and Using (*SKIP)(*FAIL) to Exclude Unwanted Matches for some more details.