I need to replace a string that could have one or more blank space in its content (at a fixed position) with another string.
[ string ]
debe ser reemplazado por:
(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:
but this only works if there aren't spaces between brackets and string. How can i build an expression to consider also whitespaces?
preguntado el 31 de julio de 12 a las 13:07
If you want to allow any whitespace use:
If you want to allow only spaces use:
myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring");
Note that you've not escaped the
] en su expresión regular.
] are regex meta-characters that mark the start and end of a character class respectively.
Así que un
[(?i)string] matches a single character that is one of
To match them literally they need to be escaped by placing a
\\ Antes que ellos.
That expression doesn't work, it only has one character class and would match a single character. You need
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.
Aquí está el código para su caso:
String myString="[ String ]"; String result = myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring");