venkat venkat - 5 months ago 22
Java Question

java regular expression find and replace multiple

I am trying to replace following code using regex in my code base.

if(StringFunctions.isNullOrEmpty(employee.getName())){

//java code
}


New code should be:

If(StringUtils.isEmpty(StringUtils.trim(employee.getName()))){

//java code
}


I have written following code to perform the update.

String regEx = "StringFunctions.isNullOrEmpty(.*)";
String replacement = "StringUtils.isEmpty(StringUtils.trim$1)";
textFromFile.replaceAll(regEx,pattern);


output is:

If(StringUtils.isEmpty(StringUtils.trim(employee.getName())){)

//java code
}


what is wrong in my code??? please help me

Answer

In regex () is the capturing group. Your regex pattern is incorrect because where you meant to put literal brackets, you have instead only put a capturing group.

The correct regex pattern is:

"StringFunctions.isNullOrEmpty\\((.+)\\)"

\\((.+)\\) means match a literal open bracket followed by (and capture) 1 or more of any character, followed by a literal closing bracket.

Testing:

String textFromFile = "if(StringFunctions.isNullOrEmpty(employee.getName())){}";
String regEx = "StringFunctions.isNullOrEmpty\\((.+)\\)";
String replacement = "StringUtils.isEmpty(StringUtils.trim($1))";
String output = textFromFile.replaceAll(regEx,replacement);
System.out.println(output);

Input:

if(StringFunctions.isNullOrEmpty(employee.getName())){}

Output:

if(StringUtils.isEmpty(StringUtils.trim(employee.getName()))){}
Comments