Flutter如何从任意字符串提取数值 无需硬编码replaceAll匹配文本
这个需求完全可以实现,你可以通过正则表达式匹配数字字符的方式完成提取,全程不需要硬编码任何待替换的文本内容。
Dart的正则表达式支持\d通配符,专门用于匹配0-9的任意数字字符,你只需要通过正则匹配提取字符串中所有符合规则的数字部分即可,无需提前指定要过滤的非数字内容。
基础实现(提取连续数字,适配你的示例)
String text = "Hello your number is: 1234"; // 匹配所有连续数字片段 Iterable<Match> numberMatches = RegExp(r'\d+').allMatches(text); // 取第一个匹配到的连续数字,就是你要的结果 String numberProvided = numberMatches.isNotEmpty ? numberMatches.first.group(0)! : ''; print("The number provided is :$numberProvided"); // 输出:1234
扩展场景1:提取字符串中所有数字(非连续数字也会拼接)
如果输入字符串类似"abc123def456",想要得到"123456"可以用下面的写法:
String text = "abc123def456"; String allNumbers = text.replaceAll(RegExp(r'[^0-9]'), ''); print(allNumbers); // 输出:123456
这里的正则[^0-9]表示匹配所有非数字的字符,直接替换为空即可,同样不需要硬编码任何具体的待替换文本。
扩展场景2:提取带小数点的数值
如果需要提取小数,调整正则即可:
String text = "当前商品价格是 29.99 元"; Iterable<Match> decimalMatches = RegExp(r'\d+\.?\d*').allMatches(text); String price = decimalMatches.isNotEmpty ? decimalMatches.first.group(0)! : ''; print(price); // 输出:29.99
内容的提问来源于stack exchange,提问作者Hammadh
相关产品推荐
相关产品推荐

