如何在Kotlin/Java中提取字符串里带千分分隔符的数字?
在Kotlin/Java中提取带千分分隔符的数字
问题场景
给定字符串:
1123 the first number is 12,345,654 and the 456 second number is 5,345 there are other numbers 123
需要从中提取所有带千分位逗号分隔的数字,最终得到结果:12,345,654 and 5,345
解决方案
使用正则表达式匹配符合千分位格式的数字,核心正则为:\d{1,3}(?:,\d{3})+,正则逻辑说明:
\d{1,3}:匹配数字开头的1-3位数字(?:,\d{3})+:非捕获组,匹配1次或多次「逗号+3位数字」的组合,确保数字符合千分位分隔规则
Kotlin 实现代码
import java.util.regex.Pattern fun extractThousandSeparatedNumbers(text: String): List<String> { val pattern = Pattern.compile("\\d{1,3}(?:,\\d{3})+") val matcher = pattern.matcher(text) val result = mutableListOf<String>() while (matcher.find()) { result.add(matcher.group()) } return result } // 测试示例 fun main() { val inputText = "1123 the first number is 12,345,654 and the 456 second number is 5,345 there are other numbers 123" val extractedNumbers = extractThousandSeparatedNumbers(inputText) // 按需求格式输出 println(extractedNumbers.joinToString(" and ")) }
Java 实现代码
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberExtractor { public static List<String> extractThousandSeparatedNumbers(String text) { Pattern pattern = Pattern.compile("\\d{1,3}(?:,\\d{3})+"); Matcher matcher = pattern.matcher(text); List<String> result = new ArrayList<>(); while (matcher.find()) { result.add(matcher.group()); } return result; } // 测试示例 public static void main(String[] args) { String inputText = "1123 the first number is 12,345,654 and the 456 second number is 5,345 there are other numbers 123"; List<String> extractedNumbers = extractThousandSeparatedNumbers(inputText); // 按需求格式输出 System.out.println(String.join(" and ", extractedNumbers)); } }
代码说明
- 编译正则表达式并创建
Matcher对象,用于遍历输入字符串 - 通过
matcher.find()循环查找所有匹配的子串,将每个符合规则的数字加入结果列表 - 最终可以通过
joinToString(Kotlin)或String.join(Java)将结果拼接成目标格式输出
内容的提问来源于stack exchange,提问作者khoshrang
相关产品推荐
相关产品推荐

