Home > Enterprise >  Match specific string not preceded with a word and any amount of whitespaces using .NET regex
Match specific string not preceded with a word and any amount of whitespaces using .NET regex

Time:11-22

I am using

Regex: (?<!WHEN\s)EMP_ID

Query: SELECT EMP_ID, CASE WHEN EMP_ID > 115 THEN 'greater' WHEN EMP_ID < 115 THEN 'lower' END AS TEST

Matches: 1 match ( EMP_ID)

But if I add any spaces after WHEN in this query, then it will show 2 matches of 'EMP_ID', which is wrong. Or if I use the where condition in my query and use this column name then also it will give me 2 matches of the column name.

How to correct this regex or use a different method to solve this issue in C#?

CodePudding user response:

You can use

(?<!WHEN\s )EMP_ID

Or, with whole word matching:

\b(?<!\bWHEN\s )EMP_ID\b

See the .NET regex demo.

Since .NET regex flavor allows unknown length patterns inside lookbehinds, the (?<!WHEN\s ) works and fails any location that is immediately preceded with WHEN one or more whitespaces.

  • Related