Home > database >  Replace all "=" but not "==" that are not in single quotes with regular expressi
Replace all "=" but not "==" that are not in single quotes with regular expressi

Time:03-20

Input

age=10 and address='a==c=d' and age==100 and abc = 22

Expected

age = 10 and address='a==c=d' and age==100 and abc = 22

Explanation:

age = 10 now has space, age==100 remains unchanged, abc = 22 becomes abc = 22, content inside single quotes is not changed

Have similar regular expressions that work for other symbols: For example ,the below expressions replace < but not <= that is not in a single quote

        joined = joined.replaceAll("<(?![=])(?=(?:[^\\\']*\\\'[^\\\']*\\\')*[^\\\']*$)", " < ");
        joined = joined.replaceAll(">(?![=])(?=(?:[^\\\']*\\\'[^\\\']*\\\')*[^\\\']*$)", " > ");
        #example: age  <=  10 and address='<==c<d' and age==100 age   <    2

Getting undesired result when using the same pattern for '='

E.g. Applying =(?![=])(?=(?:[^\']*\'[^\']*\')*[^\']*$)

on this string -> age = 10 and address='a==c=d' and age==100 , the == is also matched

May check the result in regex101

Attempted different combinations the closest I can get so far is \b(\s )?={1}(\s )?\b this matches = exactly one time with optional space on the sides. However it targets = inside single quotes as well, which is not wanted.

CodePudding user response:

https://regex101.com/r/9ySIa2/1

(?<=[^=])=(?=[^=])(?=(?:[^\']*\'[^\']*\')*[^\']*$)

=(?![=])

has been replaced with

(?<=[^=])=(?=[^=])

=(?![=]) matches an equal sign followed by not an equal sign. This means that in ==1, the first = is not matched because it's followed by an =, but the second is followed by a 1, so it gets matched.

(?<=[^=])=(?=[^=]) matches an equal sign, but only if the character before is not an equal sign ((?<=[^=]) positive lookbehind) as well as if the next character is also not an equal sign ((?=[^=]) positive lookahead)

  • Related