简体   繁体   中英

What's the best way to remove all \n \r \t from a string?

What's the best way to remove all \\n , \\r , \\t from a String in java ? Is there some sort of library and method that can do that for me nicely instead of me having to use string.replaceAll(); multiple times?

请尝试以下方法:

str.replaceAll("[\\n\\r\\t]+", "");

There is no need to do str.replaceAll multiple times. Just use a regex:

str.replaceAll("\\s+", "");

Using regex in java. for future reference, if you want to replace a more complex subset of strings

// strings that you want to remove
String regexp = "str1|str2|str3";

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regexp);

// here input is your input string
Matcher m = p.matcher(input);

while (m.find())
    m.appendReplacement(sb, "");
m.appendTail(sb);


System.out.println(sb.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM