-2

I'm trying to match a single standalone '=' character with a regular expression.

For example, for this code

if(y == 5 || x = 1) {
  Do something ...
}

I want to match to the single '=', and not the "==". I've tried a lot of combinations of regular expression strings but I still can't get a match on the correct position.

jotik
  • 17,044
  • 13
  • 58
  • 123

2 Answers2

4

You can achieve this by using a negative lookbehind and a positive lookahead:

(?<!=)=(?!=)

Example: https://regex101.com/r/uV5eC5/1

For more information about lookahead/lookbehind, read Regex lookahead, lookbehind and atomic groups

Community
  • 1
  • 1
eol
  • 23,236
  • 5
  • 46
  • 64
0

fbo's solution certainly is more elegant, but if it needs to be done in JS, which doesn't have look-behinds, you could do it with

[^=]=[^=]

Since it appears to be code you're checking, there will always be a character before and after the =, and therefore this test that neither of them is another =.

SamWhan
  • 8,296
  • 1
  • 18
  • 45
  • Both your answer and his worked after converting it to the C++ regex syntax. – Thaddeus Jones Jun 30 '16 at 08:30
  • 1
    Note that if you want to use replace afterwards, it would also replace the symbol before and the symbol after `=`. So, you could capture them as separate groups: `([^=])(=)([^=])` and then use `$1==$3` for the replace (assuming you want to replace `=` with `==`). – Maria Ivanova Jun 30 '16 at 08:35