2

I have some code containg null == myvar and want to change it myvar == null. Variants of code

if(null == myvar) > if(myvar == null)

if(null != myvar) > if(myvar != null)

if(null == myvar && someother) > if(myvar == null && someother)

if(null == foo.SomeFoo(bar).FirstOrDefault()) > if(foo.SomeFoo(bar).FirstOrDefault() == null)

I have solved the 3 first cases using this regex

null ([!=]{2}) (.*?)([ \)])

And replace with

$2 $1 null$3

Though for the last case it will replace with

if(foo.SomeFoo(bar)==null.FirstOrDefault())

The problem is it looks for a space or a parenthesis, but in the case of parenthesis it needs to balance them with opening parenthesis

I need to use Balancing Groups somehow but I do not understand how :D

Anders
  • 17,306
  • 10
  • 76
  • 144
  • Do you really need a pattern for nested parenthesis or would something like `null ([!=]{2}) ([^)( ]+(?:\([^)(]*\)[^)( ]*)*)` and replace with `$2 $1 null` suffice? Regex won't be reliable means for parsing such code. – bobble bubble Sep 18 '19 at 09:15
  • 1
    You can sort of do it badly with [`null ([!=]{2}) (?>(?\()|(?<-D>\))|[^()]+)+`](http://regexstorm.net/tester?p=null+%28%5b!%3d%5d%7b2%7d%29+%28%3f%3e%28%3f%3cD%3e%5c%28%29%7c%28%3f%3c-D%3e%5c%29%29%7c%5b%5e%28%29%5d%2b%29%2b&i=if%28null+%3d%3d+myvar+%26%26+someother%29+%0d%0aif%28null+%3d%3d+%28myvar+%26%26+someother%29%29%0d%0aif%28null+%3d%3d+foo.SomeFoo%28bar%29.FirstOrDefault%28%29%29), but then the `&&` conditions break. We *can* get these to work, but then there is a lot that will go wrong (comments, strings, ternaries, etc). Do you by any chance use Resharper? Style checks? – Kobi Sep 18 '19 at 09:18
  • 1
    One example that could go wrong: `if(null == foo.SomeFoo(")-:").FirstOrDefault())` – Kobi Sep 18 '19 at 09:19
  • The format `null==var` is a smart idea to catch the situation when you accidentally use `=` instead of `==`. In the case of the accident, you will be able to find the error quickly, thanks to the compiler error. So now I am curious: why do you want to swap the terms? – virolino Sep 18 '19 at 09:34
  • var == null is used by 9 of 10 devs in this team. We want same style. Plus var == null is easier to read than null == var – Anders Sep 18 '19 at 12:16
  • I have already fixed, it only broke on one place (last example) so I fixed it manually. but it would be fun to find a regex that can solve it – Anders Sep 18 '19 at 12:17

0 Answers0