Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match part of a string only if it is not preceded by certain characters?

I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC.

(\w{3}PRI$|[^SIG].*SEC$)

It is very close and sort of works (if I pass in "SINSEC", it returns a partial match on "NSEC"), but I don't have a good feeling about it in its current form. Also, I may have a need to add more exclusions besides "SIG" later and realize that this probably won't scale too well. Any ideas?

BTW, I'm using System.Text.RegularExpressions.Regex.Match() in C#

Thanks, Rich

like image 438
Rich Avatar asked Dec 30 '22 09:12

Rich


1 Answers

Assuming your regex engine supports negative lookaheads, try this:

((?!SIGSEC)\w{3}(?:SEC|PRI))

Edit: A commenter pointed out that .NET does support negative lookaheads, so this should work fine (thanks, Charlie).

like image 190
Dan Avatar answered Jan 17 '23 17:01

Dan