我有一个像这样的字符串
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
我想获得带有千位分隔符","的数字我该如何在kotlin或java中做到这一点?
kotlin版本的Arvind Kumar Avinash找到第一个数字的答案
val matcher = Pattern.compile("\d{1,3}(?:,\d{3})+").matcher(body)
while (matcher.find()) {
Log.e("number is: ",matcher.group())
}
您可以使用正则表达式,d{1,3}(?:,d{3})+
来查找所需的匹配项。
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());
}
}
}
:
12,345,654
5,345
正则表达式说明:
d{1,3}
: 1 ~ 3位(?:
:非抓包组启动,d{3}
:逗号后接三位数字
)
:非捕获组结束+
:一个或多个先前的令牌