简体   繁体   中英

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.

eg:

[   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?

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.

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

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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM