Reemplace una cadena con un número variable de espacios con 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.


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

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?

preguntado el 31 de julio de 12 a las 13:07

3 Respuestas

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 [ y ] en su expresión regular. [ y ] 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 (, ?, i, ), s, t, r, i, n or g

To match them literally they need to be escaped by placing a \\ Antes que ellos.

Respondido 31 Jul 12, 14:07

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

Respondido 31 Jul 12, 14:07

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

Respondido 31 Jul 12, 14:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.