Flutter Dart:如何使用正则表达式从字符串中提取数字

11

我想从一个字符串中提取数字(整数,小数或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]", "");

到目前为止,没有什么是完美的。

感谢任何帮助。

4个回答

11
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)));
}

你好,当字符串和整数之间没有空格时,比如570009,为什么会失败?另外为什么只有字符串从第二行开始才能正常工作? - Yadu
因为我回答中的正则表达式只跳过开头/结尾的空格(\s)。你可能需要类似于r'.*?(\d*).*'r'[^0-9]*([0-9]*).*'的东西。我没有测试这些示例,而且我不经常使用正则表达式,所以要小心。(仅在我的手机上) - Günter Zöchbauer

4

对于单行字符串,您可以简单地使用:

final intValue = int.parse(stringValue.replaceAll(RegExp('[^0-9]'), ''));

3
这就是我解决问题的方法:
bool isNumber(String item){
    return '0123456789'.split('').contains(item);
}

List<String> numbers = ['1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i','0'];
print(numbers);
numbers.removeWhere((item) => !isNumber(item));
print(numbers);

以下为输出结果:

[1, a, 2, b, 3, c, 4, d, 5, e, 6, f, 7, g, 8, h, 9, i, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

-1

如果要在多行字符串中检测以+国家代码开头的电话号码,请尝试这个。

\b[+][(]{0,1}[6-9]{1,4}[)]{0,1}[-\s.0-9]\b


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接