2

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

Tanishq Jaiswal
  • 177
  • 1
  • 7
  • 1
    I think you put backslash at the start of your regex by mistake. – Julia Mar 12 '21 at 20:42
  • Thanks for the comment but still not meaningful output, the current output after removing slash : allMatches : (Instance of '_RegExpMatch', Instance of '_RegExpMatch') – Tanishq Jaiswal Mar 12 '21 at 20:46

2 Answers2

1

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
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

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");
Stewie Griffin
  • 4,690
  • 23
  • 42