Search code examples
javaregexstringnumbers

Regex to extract numbers and group them with thousands separator


In my calculator app I have a string like this

String input = "-.46sin(34)*23000.34(2^3"

I want to add thousand separators to the numbers in the string so that the output would be like :

-.46sin(34)*23,000.34(2^3

How can I achieve this with regex ? The language I work with is Java and float precision is 6

Update:
final answer by Ulugbek Umirov in the comment is the correct answer
Regex :
(?<!\.\d{0,6})\d+?(?=(?:\d{3})+(?:\D|$))

Java Code :
String output = input.replaceAll("(?<!\\.\\d{0,6})\\d+?(?=(?:\\d{3})+(?:\\D|$))", "$0,");


Solution

  • The following regex can give you the idea:

    (?<!\d\.\d{0,6})\d+?(?=(?:\d{3})+(?:\D|$))
    

    Regular expression visualization

    Replace it with $0,

    Demo