Cómo reemplazar dot (.) en una cadena en Java


Tengo una Cadena llamada persons.name

Quiero reemplazar el PUNTO . con /*/ es decir, mi salida será persons/*/name

Probé este código:

String a="\\*\\";
str=xpath.replaceAll("\\.", a);

Estoy obteniendo StringIndexOutOfBoundsException.

¿Cómo puedo reemplazar el punto?

Author: Eric Leschinski, 2011-09-11

2 answers

Necesita dos barras invertidas antes del punto, una para escapar de la barra para que pase, y la otra para escapar del punto para que se convierta en literal. Las barras inclinadas hacia adelante y el asterisco se tratan literales.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

Http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

 117
Author: Femi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-06 01:04:34

Use Apache Commons Lang :

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

O con JDK independiente:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);
 8
Author: palacsint,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-11 19:52:59