javaregex

Search some string in Java code and replace it


In this java code that some one else has written, people have used null check condition as null!=abc or null==abc, but I need to change it to abc!=null and abc==null respectively.

Someone told me that this can be done using regular expressions very easily, as till now I was performing a manual task, but searching it and then replacing it manually.


Solution

  • I do not know all the requirements for what could be on the right side of the boolean expression, but assuming it is a variable name, \w will be a roughly accurate search (see http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html for the full specification of variable names).

    Search string:

    null\s*([!=]=)\s*(\w+)
    

    Replace string

    $1 $2 null