使用 Dart 语言的正则表达式

Regex using Dart lang

我正在用 dart 构建一个日志解析器。如何使用 dart 正则表达式库检索匹配值。

使用此 link 检查我的正则表达式,一切正常,如下所示:

输入这些值将为您提供:后缀、时间、级别和消息

我无法在 dart 库中使用我的正则表达式。

当 运行 在浏览器中使用 Dart 时,它使用浏览器的正则表达式引擎,if it supports named capturing groups they will be supported. If not, they won't. When running your code in Flutter, or standalone Dart, namedGroup 可以如您所愿地工作。

使用编号的捕获组并通过索引访问它们:

RegExp regExp = new RegExp(r"^(.*m)(\d{1,2}:\d{1,2}:\d{1,2},\d{1,3}) ([^\s]+) (.*)");

看到这个regex demo

在 Dart 中,尝试这样的操作:

RegExp regExp = new RegExp(r"^(.*m)(\d{1,2}:\d{1,2}:\d{1,2},\d{1,3}) ([^\s]+) (.*)");
String s = "[0m[31m22:25:57,366 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit.\"bad.war\"";
Iterable<Match> matches = regExp.allMatches(s);
for (Match match in matches) {
  print("${match.group(1)}\n");
  print("${match.group(2)}\n");
  print("${match.group(3)}\n");
  print("${match.group(4)}\n");
}

看到这个DartPad demo

对于未来的读者,正如 Scott Hyndman 在评论中解释的那样,RegExpMatch 现在支持这一点。 https://api.dartlang.org/stable/2.4.0/dart-core/RegExp-class.html

这似乎在 DartPad 中有效(至少在 dart 2.4.0 中)。 https://dartpad.dartlang.org/de5fafc572ebb786c9b4791229c65a9b