Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex using Dart lang

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 : (?<suffix>^.*m)(?<time>\d{1,2}:\d{1,2}:\d{1,2},\d{1,3}) (?<level>[^\s]+) (?<message>.*)
  • Input : [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".

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

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

like image 390
bwnyasse Avatar asked Apr 05 '26 18:04

bwnyasse


1 Answers

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]+) (.*)");

See this regex demo

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");
}

See this DartPad demo

like image 84
Wiktor Stribiżew Avatar answered Apr 08 '26 12:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!