Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make multi replace() java

I have a string with \r\n, \r, \n or \" characters in it. How can I replace them faster?

What I already have is:

String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replace("\\r\\n", "\n").replace("\\r", "").replace("\\n", "").replace("\\", ""));

But my code does not look beautiful enough. I found on the Internet something like:

replace("\\r\\n|\\r|\\n|\\", "")

I tried that, but it didn't work.

like image 499
sausagerus Avatar asked Apr 16 '26 12:04

sausagerus


1 Answers

You can wrap it in a method, put /r/n, /n and /r in a list. iterate the list and replace all such characters and return the modified string.

public String replaceMultipleSubstrings(String original, List<String> mylist){
    String tmp = original;
    for(String str: mylist){
        tmp = tmp.replace(str, "");
    }
    return tmp;
}

Test:

mylist.add("\\r");
mylist.add("\\r\\n");
mylist.add("\\n");
mylist.add("\\");  // add back slash

System.out.println("original:" + s);
String x = new Main().replaceMultipleSubstrings(s, mylist);
System.out.println("modified:" + x);

Output:

original:Kerner\r\n kyky\r hihi\n \"
modified:Kerner kyky hihi "
like image 114
Haifeng Zhang Avatar answered Apr 19 '26 01:04

Haifeng Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!