简体   繁体   English

如何仅从 flutter 中的字符串中提取数字?

[英]How to extract number only from string in flutter?

Lets say that I have a string:假设我有一个字符串:

a="23questions";
b="2questions3";

Now I need to parse 23 from both string.现在我需要从两个字符串中解析 23 。 How do I extract that number or any number from a string value?如何从字符串值中提取该数字或任何数字?

The following code can extract the number:以下代码可以提取数字:

aStr = a.replaceAll(new RegExp(r'[^0-9]'),''); // '23'

You can parse it into integer using:您可以使用以下方法将其解析为 integer:

aInt = int.parse(aStr);
const text = "23questions";

Step 1: Find matches using regex:第 1 步:使用正则表达式查找匹配项:

final intInStr = RegExp(r'\d+');

Step 2: Do whatever you want with the result:第2步:对结果做任何你想做的事:

void main() {
  print(intInStr.allMatches(text).map((m) => m.group(0)));
}

The Answer in a single line with Null Safety enabled dart. Null Safety启用 dart 的单行答案。 or Flutter 2.0 will be:或 Flutter 2.0 将是:

int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));

but be warned that it will not work with the below string:但请注意,它不适用于以下字符串:

String problemString = 'I am a fraction 123.45';

And for many people below string will be a problem too, as it will parse 2030 and not 20 or 30 .并且对于许多人来说,低于 string 也是一个问题,因为它会解析2030而不是2030

String moreProblem = '20 and 30 is friend';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM