DigitalZebra
DigitalZebra

Reputation: 41473

Java: Help with a RegEx


So, I want to replace all & in the following string with a single &. These & can be separated by one or more spaces. 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

Answers (2)

ratchet freak
ratchet freak

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

antlersoft
antlersoft

Reputation: 14786

Try:String foo = "a& & &&& & b".replaceAll("(\\s*&[\\s&]*)", "&");

Upvotes: 1

Related Questions