【问题标题】:Dart regular expression error Try calling using?Dart 正则表达式错误尝试调用使用?
【发布时间】:2021-04-18 17:08:32
【问题描述】:

我有

Error: Method 'group' cannot be called on 'RegExpMatch?' because it is potentially null.

 - 'RegExpMatch' is from 'dart:core'.

Try calling using ?. instead.

                final everything = match.group(0);

我的源代码在下面,只是一个简单的正则表达式。

我应该在哪里解决这个问题??

RegExp regExp = new RegExp(r'[0-9][0-9]');

RegExpMatch match = regExp.firstMatch(results.text);
         
final everything = match.group(0);

我是这样改源码的

  RegExp regExp = new RegExp(r'C(S|N)-[0-9][0-9][0-9]-[0-9][0-9][0-9]');

  if (regExp.hasMatch(results.text)){
     
        RegExpMatch match = regExp.firstMatch(results.text);
         
        final everything = match!.group(0);
        _showMyDialog(everything);
          
  }

仍然发生错误。

lib/camera_preview_scanner.dart:77:44: Error: A value of type 'RegExpMatch?' can't be assigned to a variable of type 'RegExpMatch' because 'RegExpMatch?' is nullable and 'RegExpMatch' isn't.

 - 'RegExpMatch' is from 'dart:core'.

                RegExpMatch match = regExp.firstMatch(results.text);

                                           ^

lib/camera_preview_scanner.dart:79:36: Warning: Operand of null-aware operation '!' has type 'RegExpMatch' which excludes null.

 - 'RegExpMatch' is from 'dart:core'.

                final everything = match!.group(0);

解决方案

使用RegExp! 代替RegExp

  RegExp! regExp = new RegExp(r'C(S|N)-[0-9][0-9][0-9]-[0-9][0-9][0-9]');

  if (regExp.hasMatch(results.text)){
     
        RegExpMatch match = regExp.firstMatch(results.text);
         
        final everything = match!.group(0);
        _showMyDialog(everything);
          
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    final everything = match!.group(0);
    

    或更好

    if(match != null){ 
       final everything = match!.group(0);
    }
    

    【讨论】:

    • 感谢您的评论我尝试使用match!但徒劳无功,我更新了文章
    • 啊,问题解决了我使用RegExpMatch?而不是 RegExpMatch
    猜你喜欢
    • 2023-04-06
    • 2020-05-31
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2016-10-21
    • 2018-09-20
    • 2014-08-07
    • 2016-08-31
    相关资源
    最近更新 更多