Replace full (almost equal) words in Java

2

I am writing a program and I need to replace some words with others, but sometimes the words can be similar.

Words do not have spaces, and they are always complete words.

Example:

String[] palabrasAcambiar = {"pan","pan2"};
String[] valores = {"pan1","pan2"};
String oracion = "el pan es mejor que el pan2";

//REEMPLAZAR PALABRAS POR VALORES
for (int i = 0; i < 2; i++) {
    oracion = oracion.replace(palabrasAcambiar[i],valores[i]);  
}
//resultado: el pan1 es mejor que el pan12
//resultado deseado:  el pan1 es mejor que el pan2

I already know that I change the "bread" of the "pan2" for "pan1" and it turned out the "pan12" < - lol

Well .. I wanted to know if anyone knows how to deal with this problem?

    
asked by centenond 12.10.2016 в 09:41
source

1 answer

2

As long as it is words (consisting of letters, numbers or underscore) complete (no letters, numbers or underscores before or after), using regular expressions, you can use the full word limit \b In addition, we use Pattern.quote ( ) to escape any metacharacter that might be in the searched words.

import java.util.regex.*;
String[] palabras = {"pan","pan2"};
String[] valores = {"pan1","pan2"};
String oracion = "el pan es mejor que el pan2";

//REEMPLAZAR PALABRAS POR VALORES
for (int i = 0; i < 2; i++) {
    oracion = oracion.replaceAll("\b"+Pattern.quote(palabras[i])+"\b",valores[i]);  
}

System.out.println(oracion);

Result:

el pan1 es mejor que el pan2

Demo in Ideone

    
answered by 12.10.2016 / 10:17
source