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?
If you want to allow any whitespace use:
If you want to allow only spaces use:
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,norgTo match them literally they need to be escaped by placing a
\\before them.