regex - 如何在 Dart 中使用正则表达式?

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

感谢任何帮助!

正则表达式:/^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 .

另见:

  • Extracting text from a string with regex groups in Dart

https://stackoverflow.com/questions/49757486/

相关文章:

flutter - 如何在 flutter 中获得唯一的设备ID?

gridview - Flutter GridView 页脚(用于指示无限滚动的负载)

android - 如何在 Flutter App 中处理 onPause/onResume?

android - 如何在 Flutter 中获取 AppBar 高度

listview - Flutter:SimpleDialog 中的 ListView

dart - Flutter - 容器中的顶部对齐文本

google-maps - 如果可以使用 flutter 打开谷歌地图应用程序

flutter - 如何在 flutter 小部件测试中捕获来自 future 的错误?

dart - 如何格式化定位文本 block 的背景颜色?

android - Flutter - 导航到新屏幕,并清除所有以前的屏幕