TransWikia.com

Replace .(dot) inside number Java between two elements

Stack Overflow Asked by Alex Danilov on December 27, 2021

I have this String:

String str = "<p>23.5</p>";

And i want to replace the dot for comma only inside

elements. The output i need is:

<p>23,5</p>

I cant figure it out, i have this:

str = str.replaceAll("(?<=<p>)\.(?=</p>)", ",");

But it doesnt work. I need to replace dot only in elements with particular tag (is an xml in a String), in this case

.

Thank you

2 Answers

Following regex will match the dot character that is between numerical characters

(?<=d).(?=d)

Regex Explanation:

  • d - match any digit between 0-9
  • (?<=d). - positive look-behind to match any . character that has a digit just before it
  • .(?=d) - positive look-ahead to match any . character that has a digit just after it

Demo:

https://regex101.com/r/WMEjPl/1

Java Code Example:

public static void main(String args[]) {
   String regex = "(?<=\d)\.(?=\d)";
  
   String str = "<p>23.5</p>";
   String str2 = "Mr. John <p>23.5</p> Hello";
   String str3 = "Mr. John <p>23.5</p> Hello 12.2324";

   System.out.println(str.replaceAll(regex, ","));   // <p>23,5</p>
   System.out.println(str2.replaceAll(regex, ","));  // Mr. John <p>23,5</p> Hello
   System.out.println(str3.replaceAll(regex, ","));  // Mr. John <p>23,5</p> Hello 12,2324
}

Answered by Yousaf on December 27, 2021

You may use capturing groups + escape the /:

str = str.replaceAll("(?<=<p>)(\d*)\.(\d+)(?=<\/p>)", "$1,$2");

If you want to replace dot in all numbers, you may just as well use

str = str.replaceAll("(\d*)\.(\d+)", "$1,$2");

Answered by Andrew Vershinin on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP