正则表达式使用Dart lang [英] Regex using Dart lang

查看:93
本文介绍了正则表达式使用Dart lang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用dart构建日志解析器.如何使用dart regex库检索匹配值.

I'm building a log parser in dart. How can I use dart regex library to retrieve matching values.

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

Using this link to check my regex, everything is ok wih the following :

  • Regex:(?<后缀> ^.* 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"

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

Entering these values will give you : suffix, time , level and message

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

I'm not able to use my regex with the dart library.

推荐答案

在浏览器中运行Dart时,它将使用浏览器的正则表达式引擎和 namedGroup 可以正常工作.

When running Dart in a browser, it uses the browser's regex engine, and 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 works as you'd expect.

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

Use numbered capturing groups and access them by their indices:

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

参见此 regex演示

在Dart中,尝试以下操作:

In Dart, try something like this:

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演示

这篇关于正则表达式使用Dart lang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆