nowox
nowox

Reputation: 29086

Matching operator only with an regex

With this example, I am trying to only match operators in C-like code in order to add a space before and after it

For instance a+b should become a + b but a + b shouldn't become a + b. The other tricky thing is I shouldn't add a space in case of negative numbers like -2. Of course I need to be aware of all the exceptions like the text in comments like // work-around.

Here's the regex that I'm working on:

(?!= |=|&|\||%)(\+|-)(?! |=|\1)

Unfortunately the negative-lookaround doesn't work as expected. How can I fix it?

Upvotes: 0

Views: 43

Answers (1)

user557597
user557597

Reputation:

This is just to help your regex a little.
The first (negative) lookahead, should be a (negative) lookbehind.

I don't think this is going to help with parsing math symbols though.

http://regex101.com/r/lX3aF6/1

 # (?<!=[ ])(?<![=&|%])(\+|-)(?!\1|[ =])

 (?<! = [ ] )
 (?<! [=&|%] )
 ( \+ | - )
 (?! \1 | [ =] )

Upvotes: 1

Related Questions