How to return/print matches on a string in RegEx in Flutter/Dart?

Viewed 1906

I want to return a pattern through regEx in flutter every time it' found, I tested using the Regex operation it worked on the same string, returning the match after that included match 'text:' to '}' letters, but it does not print the matches in the flutter application.

The code I am using:

String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
print("allMatches : "+exp.allMatches(myString).toString());

The output print statement is printing I/flutter ( 5287): allMatches : (Instance of '_RegExpMatch', Instance of '_RegExpMatch') instead of text: PM

Following is the screenshot of how it is parsing on regexr.com

enter image description here

2 Answers

Instead of using a non greedy match with a lookahead, I would suggest using a negated character class matching any char except } in capture group 1, and match the } after the group to prevent some backtracking.

\b(text:[^}]+)}

You can loop the result from allMatches and print group 1:

String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"\b(text:[^}]+)}");
for (var m in exp.allMatches(myString)) {
    print(m[1]);    
}

Output

text: PM

You need to use map method to retrieve the string from the matches:

String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");

final matches = exp.allMatches(myString).map((m) => m.group(0)).toString();

print("allMatches : $matches");
Related