Home > Back-end >  Extract two numbers with thousand spliters from a string
Extract two numbers with thousand spliters from a string

Time:12-23

I have a string like this

1123 the first number is 12,345,654 and the 456 second number is 5,345 there are other numbers 123

desired output is 12,345,654 and 5,345

I want to get numbers with thousand separator "," how should i do this in kotlin or java?

kotlin version of Arvind Kumar Avinash answer which finds the first number

val matcher = Pattern.compile("\\d{1,3}(?:,\\d{3}) ").matcher(body)
while (matcher.find()) {
    Log.e("number is: ",matcher.group())
}

CodePudding user response:

You can use the regex, \d{1,3}(?:,\d{3}) to find the desired matches.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String str = "1123 the first number is 12,345,654 and the 456 second number is 5,345 there are other numbers 123";
        Matcher matcher = Pattern.compile("\\d{1,3}(?:,\\d{3}) ").matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

Output:

12,345,654
5,345

Explanation of the regex:

  • \d{1,3}: One to three digits
  • (?:: Start of non-capturing group
    • ,\d{3}: Comma followed by three digits
  • ): End of non-capturing group
  • : One or more of the previous token
  • Related