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?
Asked
Active
Viewed 5,644 times
0

thegauravmahawar
- 2,802
- 3
- 14
- 23

goe
- 1,153
- 2
- 12
- 24
-
4Why multiple times? The parameter to `replaceAll` is a regular expression. – RealSkeptic Oct 21 '15 at 14:47
-
4Possible duplicate of [how to remove the \n, \t and spaces between the strings in java?](http://stackoverflow.com/questions/2461331/how-to-remove-the-n-t-and-spaces-between-the-strings-in-java) – morels Oct 21 '15 at 14:47
3 Answers
6
Please try this:
str.replaceAll("[\\n\\r\\t]+", "");

Tsung-Ting Kuo
- 1,171
- 6
- 16
- 21
-
The answer of @morels is more elegant than mine, but it will also replace whitespace (which is not specified to be removed in the question). My solution focus on replacing \n \r \t only. Thanks! – Tsung-Ting Kuo Oct 21 '15 at 14:59
4
There is no need to do str.replaceAll
multiple times.
Just use a regex:
str.replaceAll("\\s+", "");

morels
- 2,095
- 17
- 24
-
2This will also remove `\x0B` and `\f` as well as whitespace, so might be too much of a sledgehammer approach if those characters are required... – JonK Oct 21 '15 at 15:00
-
1remove singular characters as well, `str.replaceAll("[\\n\\r\\t]+", "");` like @Tsung-Ting Kuo does – morels Oct 21 '15 at 15:03
-
1Maybe replace such a sequence with a single space, otherwise the text is squashed. And end with a `.trim()` – Joop Eggen Oct 21 '15 at 15:29
2
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());

AbtPst
- 7,778
- 17
- 91
- 172