Hitesh Ghuge
Hitesh Ghuge

Reputation: 823

replaceAll("match","replace") in java

is there any efficient way to do multiple replaceAll("match","replace").

I'm finding match using regex and replace. e.g.

public static String replacePattern(String line)
{
 if(line != null || !"".equals(line)) 
  {
    line = line.replaceAll("regexPattern_1","replacce_1");
    line = line.replaceAll("regexPattern_2","replacce_2"); 
    line = line.replaceAll("regexPattern_3","replacce_3");
    line = line.replaceAll("regexPattern_4","replacce_4");

    .
    .
    .
    line = line.replaceAll("regexPattern_N","replacce_N");
    return line;
  }
 return line;
}

I don't want code look good, to me Perf is important

Upvotes: 0

Views: 149

Answers (3)

user6098752
user6098752

Reputation:

Not sure whether efficiency could be improved. But you can make it look good. If you want more elegance, you can use recursion which will need some additional work for termination.

public static String replacePattern(String line)
{
  //intitialize String[] repl with items to be replaces
  //initialize String[] pattern with corresponding replacements
  for(int i = 0; i<repl.length; i++)
     if(line != null || !"".equals(line)) 
        line = line.replaceAll(repl[i],pattern[i]);

 return line;
}

Upvotes: 1

Pooya
Pooya

Reputation: 6136

I'm not sure what you mean by shorter but if you want shorter texts to write you can use:

line = line.replaceAll("regexPattern_1","replacce_1")
           .replaceAll("regexPattern_2","replacce_2") 
           .replaceAll("regexPattern_3","replacce_3")
           .replaceAll("regexPattern_4","replacce_4")
           .
           .
           .
           .replaceAll("regexPattern_N","replacce_N");

Or:

String[] patterns = new String[] {"pattern1",....};
String[]  replace = new String[] {"replace1",....};

for(int i=0; i<patterns.length; i++)
{
   line = line.replaceAll(patterns[i],replace[i]);
}

Upvotes: 1

Since Strings are immutable another way to handle this:

str.replaceAll("a", "b").replaceAll("c", "d").replaceAll("e", "f");

Upvotes: 1

Related Questions