Home > OS >  Regular Expression to match word NOT preceded with a period
Regular Expression to match word NOT preceded with a period

Time:11-10

I have this regular expression Regular Expression

What I'm trying to do is to have it NOT match a line where the word DebtCloud is preceded by a period, and that is why I have put (?!\.) in there between .* and \b, and yet, the last row in the test sample is matched, when it shouldn't because there is a period before DebtCloud.

What am I doing wrong?

CodePudding user response:

Trivially, you were using negative lookaheads for both the dot after DebtCloud and also before it (incorrect). Use a negative lookbehind in front of DebtCloud and your pattern works:

^(?!using |namespace ).*(?<!\.)\b[Dd]ebt[Cc]loud\b(?!\.)

Demo

Note also that you might find this version acceptable:

^(?!using |namespace ).*(?<!\S)[Dd]ebt[Cc]loud(?!\S)

Here we are simply asserting that DebtCloud is surrounded on both sides by either spaces or the start/end of the input. This is not the same exact logic as you have, but it may fit your needs.

  • Related