regex - Flutter Dart:如何使用 RegEx 从字符串中提取数字
问题描述
我想从字符串中提取一个数字(整数、十进制或 12:30 格式)。我使用了以下正则表达式,但无济于事:
final RegExp numberExp = new RegExp(
"[a-zA-Z ]*\\d+.*",
caseSensitive: false,
multiLine: false
);
final RegExp numberExp = new RegExp(
"/[+-]?\d+(?:\.\d+)?/g",
caseSensitive: false,
multiLine: false
);
String result = value.trim();
result = numberExp.stringMatch (result);
result = result.replaceAll("[^0-9]", "");
result = result.replaceAll("[^a-zA-Z]", "");
到目前为止,没有什么是完美的。
任何帮助表示赞赏。
解决方案
const text = '''
Lorem Ipsum is simply dummy text of the 123.456 printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 12:30 unknown printer took a galley of type and scrambled it to make a
23.4567
type specimen book. It has 445566 survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
''';
final intRegex = RegExp(r'\s+(\d+)\s+', multiLine: true);
final doubleRegex = RegExp(r'\s+(\d+\.\d+)\s+', multiLine: true);
final timeRegex = RegExp(r'\s+(\d{1,2}:\d{2})\s+', multiLine: true);
void main() {
print(intRegex.allMatches(text).map((m) => m.group(0)));
print(doubleRegex.allMatches(text).map((m) => m.group(0)));
print(timeRegex.allMatches(text).map((m) => m.group(0)));
}
推荐阅读
- maven - 使用包含部分输入路径的输出路径复制资源
- vue.js - 在 VueX 中存储多个 Axios 请求的最佳方式是什么?
- c# - 将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其正常
- mongoose - 收到错误“throw new mongoose.Error.MissingSchemaError(name); MissingSchemaError:”
- scala - 如何在数据框中附加列值
- label - 自定义工具提示内容@ngx-charts | 角2+ | 打字稿
- python - 如何通过 cython 将 MPI 通信器从 python 传递到 C?
- database - Laravel 单元测试独立数据库
- json - JSON Schema 仅针对数组的第一个元素报告错误
- asp.net - 发布集合 - 在表格行上添加类时为空/null