Reputation: 41473
So, I want to replace all &
in the following string with a single &
. These &
can be separated by one or more space
s. I have a sample input string and a code snippet of what I have.
Input string:
a& & &&& & b
Here is what I have so far:
String foo = "a& & &&& & b".replaceAll("(\\s*&+\\s*&\\s*)", "&");
System.out.println(foo); // prints: "a&&b"
// expected: "a&b"
I'm not sure why two &
are ending up in the result.
Any hlep would be appreciated. Thanks!
Upvotes: 0
Views: 55
Reputation: 48196
why make it more complicated than it needs to be
"(\\s*&)+\\s*"
one or more (sequences of &
preceded by zero or more whitespace) followed by zero or more whitespace
Upvotes: 3
Reputation: 14786
Try:String foo = "a& & &&& & b".replaceAll("(\\s*&[\\s&]*)", "&");
Upvotes: 1