在 Flutter 应用程序中,我需要检查字符串是否与特定的正则表达式匹配。但是,我从应用程序的 JavaScript 版本复制的正则表达式always在 Flutter 应用程序中返回 false。我验证了regexr https://regexr.com/该正则表达式是有效的,并且该正则表达式已经在 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
对于未来的观众来说,这是一个更普遍的答案。
Dart 中的正则表达式的工作方式与其他语言非常相似。您使用RegExp https://api.dartlang.org/stable/2.2.0/dart-core/RegExp-class.html类来定义匹配模式。然后使用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
提取文本
final myString = '25F8..25FF ; Common # Sm [8] UPPER LEFT TRIANGLE';
// find a variable length hex value at the beginning of the line
final regexp = RegExp(r'^[0-9a-fA-F]+');
// find the first match though you could also do `allMatches`
final match = regexp.firstMatch(myString);
// group(0) is the full matched text
// if your regex had groups (using parentheses) then you could get the
// text from them by using group(1), group(2), etc.
final matchedText = match?.group(0); // 25F8
还有一些例子here https://github.com/suragch/string_validator/blob/master/lib/src/validator.dart.
也可以看看:
- 在 Dart 中使用正则表达式组从字符串中提取文本 https://medium.com/flutter-community/extracting-text-from-a-string-with-regex-groups-in-dart-b6be604c8a69?sk=a0c94b1a6fba950dfef380d67f5b858e
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)