Reputation: 49321
I am trying to replace all NewLines in a StringBuilder with nothing, and I thought this would work...but it doesn't.
Pattern replace = Pattern.compile("\\n");
Matcher matcher2 = replace.matcher(sb);
matcher2.replaceAll("");
What am I missing? Thanks
Upvotes: 0
Views: 2668
Reputation: 7899
Matcher.replaceAll("blah")
returns String
so there is nothing about performing operation on StringBuilder. However you are not using any method of StringBuilder
except toString()
. StringBuilder
are mutable but in your case you are using Matcher
class replace the string.
Answer is just capture replaced string in a variable.
String str= matcher2.replaceAll("");
You can understand this by simple below example.
StringBuffer sb=new StringBuffer("I love JAVA");
Pattern replace = Pattern.compile("love");
Matcher matcher2 = replace.matcher(sb.toString());
String s=matcher2.replaceAll("hate");
System.out.println(sb.toString());
System.out.println(s);
Prints:
I love JAVA
I hate JAVA
Sb
has not been changed yet.
Upvotes: 1
Reputation: 159754
Strings
are immutable so
matcher2.replaceAll("");
will return a new String
without altering the StringBuilder
. Just use the result
String result = matcher2.replaceAll("");
Upvotes: 0