【问题标题】:How to extract number only from string in flutter?如何仅从颤动的字符串中提取数字?
【发布时间】:2020-08-07 15:16:03
【问题描述】:

假设我有一个字符串:

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

现在我需要从两个字符串中解析 23。如何从字符串值中提取该数字或任何数字?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    const text = "23questions";
    

    第 1 步:使用正则表达式查找匹配项:

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

    第 2 步:对结果做任何你想做的事:

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

    【讨论】:

    • 谢谢。它有效,但我觉得上述解决方案就足够了,而且会更干净。
    【解决方案2】:

    以下代码可以提取数字:

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

    您可以使用以下方法将其解析为整数:

    aInt = int.parse(aStr);
    

    【讨论】:

    • 单行版本:int intValue = int.parse(myString.replaceAll(RegExp('[^0-9]'), ''));
    猜你喜欢
    • 2021-01-08
    • 2021-07-18
    • 2016-12-13
    • 1970-01-01
    • 2019-09-14
    • 2015-10-04
    • 2021-11-14
    • 2021-07-28
    • 2019-06-03
    相关资源
    最近更新 更多