Ivan
Ivan

Reputation: 4234

Replace a string with variable number of spaces with replaceAll

I need to replace a string that could have one or more blank space in its content (at a fixed position) with another string.

e.g:

[   string   ] 

must be replaced with:

anotherstring

(where there could be more or less or none blank spaces between " and string). And also the replacement must be case insenitive. Actually i'm using that expression:

myString.replaceAll("[(?i)string]", "anotherstring"); 

but this only works if there aren't spaces between brackets and string. How can i build an expression to consider also whitespaces?

Upvotes: 3

Views: 989

Answers (3)

ali
ali

Reputation: 391

You need to include the regular expressions to match the spaces as well, that is a whitespace followed by a * which matches any number of instances of the whitespace, including no whitespace. If you need at least one whitespace, you can replace those with a + sign.

Here's the code for your case:

String myString="[      String      ]";
String result = myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring"); 

Upvotes: 2

codaddict
codaddict

Reputation: 455152

If you want to allow any whitespace use:

myString.replaceAll("\\[\\s*(?i)string\\s*\\]", "anotherstring"); 

If you want to allow only spaces use:

myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring"); 

Note that you've not escaped the [ and ] in your regex. [ and ] are regex meta-characters that mark the start and end of a character class respectively.

So a [(?i)string] matches a single character that is one of (, ?, i, ), s, t, r, i, n or g

To match them literally they need to be escaped by placing a \\ before them.

Upvotes: 4

Marko Topolnik
Marko Topolnik

Reputation: 200166

That expression doesn't work, it only has one character class and would match a single character. You need "(?i)\\[\\s*string\\s*\\]".

Upvotes: 3

Related Questions