Looping with RegEx and replacing the current match

Consider the following line:

He ordered pizza with anchovies. Unfortunately, this was not what he wanted. In addition, pizza with mushrooms, pepperoni and anchovies is much better than regular pizza with anchovies.

Say what you need to change pizza with (ingredients)to pizza with (ingredients) on a thin crust.

To do this, I installed Regex:

(?i:pizza with [a-zA-Z,\s]*?anchovies)

It captures three matches. Then I continue to add on a thin crustto each match using the following code:

Pattern p = Pattern.compile("(?i:pizza with [a-zA-Z,\s]*?anchovies)");
Matcher m = p.matcher(string);
while(m.find())
{
    string = string.replace(m.group(), m.group() + "on a thin crust.");
}

The result of this will be:

He ordered pizza with anchovies on a thin crust on a thin crust. Unfortunately, this was not what he wanted. In addition, pizza with mushrooms, pepperoni and anchovies is much better than regular pizza with thin crust anchovies and thin crust.

What happened:

pizza with anchovies . , String.replace pizza with anchovies on a thin crust. , , replace ( ). , double on a thin crust.

:

Regex ?

+6
1

replaceAll, $0 :

String s = "He ordered a pizza with anchovies. Unfortunately, it wasn't the thing he wanted. Besides, pizza with mushroom, pepperoni and anchovies is much better than the normal pizza with anchovies.";
s = s.replaceAll("(?i)pizza with [a-zA-Z,\\s]*?anchovies", "$0 on a thin crust");
System.out.println(s);
// => He ordered a pizza with anchovies on a thin crust. Unfortunately, it wasn't the thing 
//    he wanted. Besides, pizza with mushroom, pepperoni and anchovies on a thin crust is 
//    much better than the normal pizza with anchovies on a thin crust.

Java

, , replaceAll() , , , .

+6

Source: https://habr.com/ru/post/1016669/


All Articles