小编典典

如何在Dart中使用RegEx?

flutter

在Flutter应用程序中,我需要检查字符串是否匹配特定的RegEx。但是,我从应用程序的JavaScript版本复制的RegEx
在Flutter应用程序中 始终
返回false。我在regexr上验证了RegEx有效,并且该正则表达式已经在JavaScript应用程序中使用,因此应该正确。

任何帮助表示赞赏!

正则表达式: /^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i

测试代码:

RegExp regExp = new RegExp(
  r"/^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i",
  caseSensitive: false,
  multiLine: false,
);
print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString());
print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString());
print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString());
print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());

输出:

allMatches : ()
firstMatch : null
hasMatch : false
stringMatch : null

阅读 1037

收藏
2020-08-13

共1个答案

小编典典

我认为您已尝试在原始表达式字符串中包含选项,而您已经将其作为RegEx的参数(对于大小写不敏感的/ i声明为caseSensitive:false)。

// Removed /i at the end
// Removed / in front - Thanks to Günter for warning
RegExp regExp = new RegExp(
  r"^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789",
  caseSensitive: false,
  multiLine: false,
);
print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString());
print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString());
print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString());
print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());

给出:

allMatches : (Instance of '_MatchImplementation')
firstMatch : Instance of '_MatchImplementation'
hasMatch : true
stringMatch : WS://127.0.0.1:56789
2020-08-13