Reputation: 1340
Why does this code not work?
public static void main(String[] args) {
String s = "You need the new version for this. Please update app ...";
System.out.println(s.replaceAll(". ", ".\\\\n").replaceAll(" ...", "..."));
}
This is my wanted output:
You need the new version for this.\nPlease update app...
Thanks for the information
Upvotes: 3
Views: 2886
Reputation: 213223
String.replaceAll
method takes Regex as first argument.
So you need to escape your dot (.
), as it has special meaning in Regex, which matches any character.
System.out.println(s.replaceAll("\\. ", ".\\\\n").replaceAll(" \\.\\.\\.", "..."));
However, for your given input, you can simply use String.replace
method, as it does not take Regex
, and has an added advantage of that.
Upvotes: 3
Reputation: 129497
You shouldn't be using replaceAll
- use replace
instead. replaceAll
takes a regular expression when it is not needed here (and hence it will be unnecessarily inefficient).
String s = "You need the new version for this. Please update app ...";
System.out.println(s.replace(". ", ".\\n").replace(" ...", "..."));
(Also note that I've replaced ".\\\\n"
with ".\\n"
here, which produces the desired output.)
Upvotes: 1
Reputation: 135992
try as
System.out.println(s.replace(". ", ".\n").replace(" ...", "..."));
this gives
You need the new version for this.
Please update app...
Upvotes: 0
Reputation: 37813
.
is a special regex character and will match anything. You need to escape it like this: \\.
So to match three dots you must use following regex: "\\.\\.\\."
what you want is
s.replaceAll("\\. ", ".\n").replaceAll(" \\.\\.\\.", "...")
Upvotes: 1