Friday, July 26, 2019

Regex to find a string NOT followed by another

Visual studio has slightly different regex syntax. Thus the not symbol is ?! instead of ^ in normal regex.


Lets say we want to find all occurrences of StrA NOT followed by StrB and replace them with StrC

that is given the following data


StrA
StrB
StrAStrB
StrAXYZ
XYZStrA
StrBXYZ

We would like out output to be

StrC         //replaced  StrA since it is not being followed by StrB
StrB
StrAStrB
StrCXYZ      //replaced  StrA since it is not being followed by StrB
XYZStrC      //replaced  StrA since it is not being followed by StrB
StrBXYZ

The regular expression for find is: \b([a-zA-Z0-9_]*)StrA(?!StrB)([a-zA-Z0-9_]*)\b
And for replace is:                          $1StrC$2

No comments:

Regex obfuscate email

 Use this code in C# to obfuscate email using regex // Online C# Editor for free // Write, Edit and Run your C# code using C# Online Compile...