2

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.

5
  • 4
    Out of curiosity: why do you have to change it? Commented Jul 13, 2011 at 17:23
  • @haward : One of managers have told me.. even i don't know why.. just i need to change.. Commented Jul 13, 2011 at 17:24
  • What editor/environment/ide are you doing this in-- that's relevant for how you would do the regex Commented Jul 13, 2011 at 17:24
  • Are you sure you want to change null==abc to abc=null? Those have two different meanings (hint hint, one is assignment) Commented Jul 13, 2011 at 17:52
  • @mrk: have updated the question.Please check now. Commented Jul 13, 2011 at 19:00

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

You should replace \s+ with \s* to match also the examples given by OP.
@Howard thank you, I think that is what I was thinking, don't know why I put +.
@Renesis : i tried with the above one. First the replace string should be $2 $1 null, and more over this works only with simple conditions, not for complex conditions. I am also reading the same, and will comment once i am able to find something.
@Renesis : do u have any idea how to do .. i tried many cases but all does not work properly
0

It cannot be done correctly with regular expressions.

Consider

/*
Print whether null==abc.
*/
System.out.print("null==abc : " + (null==abc));

If you want to change only the code, the third null==abc above, then you can get unintended changes to string and comment content by naively using regular expression replaces to change code.

And you want to be careful to not change

null==abc.def

to

abc==null.def

or to change

null==abc(def)

to

abc==null(def)

If you're OK with potential string and comment changes, and are going to review the changes to make sure you didn't break any method calls, then you can always do this in perl.

perl -i.bak -pe 's/null(\s*[!=]=\s*)([\w.]+)/$2$1null/g' YourJavaFile.java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.