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
asked Apr 16, 2016 at 10:56
Hitesh Ghuge
8432 gold badges11 silver badges43 bronze badges
3 Answers 3
Since Strings are immutable another way to handle this:
str.replaceAll("a", "b").replaceAll("c", "d").replaceAll("e", "f");
answered Apr 16, 2016 at 11:05
ΦXocę 웃 Пepeúpa ツ
48.4k17 gold badges77 silver badges102 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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]);
}
answered Apr 16, 2016 at 11:02
Pooya
6,1563 gold badges25 silver badges43 bronze badges
Comments
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;
}
answered Apr 16, 2016 at 11:12
user6098752
4 Comments
Pooya
what do you mean by recursion?
Pooya
not a good solution for this case which can be solved with one line for loop
lang-java
replaceAll("a","b")and thenreplaceAll("b","c")possible? What result would you want to achieve for input likeabc? Should it bebccorccc?