【问题标题】:Regex using Dart lang使用 Dart 语言的正则表达式
【发布时间】:2016-12-14 18:49:55
【问题描述】:

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

使用link 检查我的正则表达式,一切正常:

  • 正则表达式:(?<suffix>^.*m)(?<time>\d{1,2}:\d{1,2}:\d{1,2},\d{1,3}) (?<level>[^\s]+) (?<message>.*)
  • 输入:[0m[31m22:25:57,366 错误[org.jboss.msc.service.fail](MSC服务线程1-8)MSC000001:无法启动服务jboss.deployment.unit。“bad.war” .

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

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

【问题讨论】:

  • 什么是有效值?
  • 试试regexr.com Dart 只支持 JS RegExp 支持的 xxxToJS 可转译。
  • 使用编号的捕获组:^(.*m)(\d{1,2}:\d{1,2}:\d{1,2},\d{1,3}) ([^\s]+) (.*) 并使用编号索引访问它们。
  • 感谢@GünterZöchbauer 编辑原始答案。有效值为 suffix=[0m[31m , time=22:25:57,366 , level=error, message=....
  • @WiktorStribiżew 如何在 dart Regex 中使用编号的捕获组?

标签: regex dart dart-pub


【解决方案1】:

在浏览器中运行 Dart 时,它使用浏览器的正则表达式引擎,if it supports named capturing groups 它们将被支持。如果没有,他们不会。在 Flutter 或独立 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

【讨论】:

【解决方案2】:

对于未来的读者,正如 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

【讨论】:

  • 不,它在 dartpad 中不起作用。它在 2.4.1 中引发错误。
  • 嗨 Gaurav,如果您尝试提供的 dartpad 链接,它可以工作吗?它对我有用。
  • 嗨,Gav,它在这里工作。
猜你喜欢
  • 2019-07-26
  • 2013-11-18
  • 1970-01-01
  • 2011-01-31
  • 2021-06-29
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多