如何在Dart中使用RegEx?

问题描述 投票:10回答:2

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

任何帮助表示赞赏!

RegEx:/^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
regex dart flutter
2个回答
13
投票

我认为您尝试在原始表达式字符串中包含选项,而您已将其作为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

2
投票

对于未来的观众来说,这是一个更普遍的答案。

Dart中的Regex与其他语言非常相似。您可以使用RegExp类来定义匹配模式。然后使用hasMatch()测试字符串上的模式。

Examples

字母数字

final alphanumeric = RegExp(r'^[a-zA-Z0-9]+$');
alphanumeric.hasMatch('abc123');  // true
alphanumeric.hasMatch('abc123%'); // false

六角形颜色

RegExp hexColor = RegExp(r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');
hexColor.hasMatch('#3b5');     // true
hexColor.hasMatch('#FF7723');  // true
hexColor.hasMatch('#000000z'); // false

还有一些例子here

© www.soinside.com 2019 - 2024. All rights reserved.