Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a single equals sign with regular expressions?

Tags:

c#

regex

match

I have the following expression:

if(x == a+b) b=a+2; else x = 1;

I need to match a single equal sign =. Not ==, not ==== and so on. And it should match without spaces around the sign, just equals sign. I have quite a monster-like reg. expression which matches everything in the code above, everything I need but the single equals sign. Here is my expr:

 /\bif\b|\belse\b|\(|\)|\+|\-|\*|\\|\>|\<|\<=|\>=|(?<![!=])[!=]=(?!=)|([a-zA-Z][a-zA-z0-9_]*)|(\d+\.?\d*)/g

Although it may be not optimal variant (I'm sure it's not:)), I need to add the "equals match" through the pipe | into my expression.

Strange it may seem, but I didn't find the solution searching through stackoverflow questions...

like image 319
Denis Yakovenko Avatar asked Dec 19 '22 06:12

Denis Yakovenko


2 Answers

You need to use a look-ahead and look-behind zero length assertion. The regex you are looking for should be (?<!=)=(?!=). This demands that we find a = not preceeded by an equals sign (?<!=) and not followed by an equals sign (?!=).

like image 136
Erik Avatar answered Jan 31 '23 00:01

Erik


This is the most simple i can come up with:

(?<!=)=(?!=)
like image 30
CSharpie Avatar answered Jan 31 '23 00:01

CSharpie