在 Flutter 应用程序中,我需要检查字符串是否与特定的 RegEx 匹配。但是,我从应用程序的 JavaScript 版本复制的 RegEx always 在 Flutter 应用程序中返回 false。我在 regexr 上进行了验证RegEx 是有效的,并且这个 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
最佳答案
对于 future 的观众来说,这是一个更普遍的答案。
Dart 中的正则表达式的工作方式与其他语言非常相似。您使用 RegExp
类来定义匹配模式。然后使用 hasMatch()
在字符串上测试模式。
字母数字
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://stackoverflow.com/questions/49757486/