A Match in Dart is the result of searching for a sequence in a string. The Match
object is returned whenever pattern matching methods are applied on strings using the RegExp
class in Dart.
The example below shows how the allMatches
method of the RegExp
class returns an iterable of Match
objects that match sequences of digits against a string:
import 'dart:convert';void main() {String str = 'I have 23 apples, 42 oranges and 6 bananas.';//Declaring a RegExp object with a pattern that matches sequences of digitsRegExp reg = new RegExp(r'(\d+)');//Iterating over the matches returned from allMatchesIterable allMatches = reg.allMatches(str);var matchCount = 0;allMatches.forEach((match) {matchCount += 1;print('Match ${matchCount}: ' + str.substring(match.start, match.end));});}
The Match
class includes several useful properties:
Match.start
→ int
: Returns the index of the string where the match starts.Match.end
→ int
: Returns the index of the string one after where the match ends.Match.groupCount
→ int
: Returns the total number of captured groups in the match.Match.input
→ String
: Returns the string on which pattern matching has been done.Match.pattern
→ Pattern
: Returns the pattern used to search the input string.Groups are substrings that were part of some pattern’s matchings.
The class also has a couple of handy methods to work with groups:
Match.group(int group)
→ String
: Returns the string matched by group
.Match.groups(List<int> groupIndices)
→ List<String>
: Returns a list of the groups with the given indices.Let’s see how these class attributes work with the same example we worked with above:
import 'dart:convert';void main() {String str = 'I have 23 apples, 42 oranges and 6 bananas.';//Declaring a RegExp object with a pattern that matches sequences of digitsRegExp reg = new RegExp(r'(\d+)');//Iterating over the matches returned from allMatchesIterable allMatches = reg.allMatches(str);var matchCount = 0;allMatches.forEach((match) {matchCount += 1;print('Match ${matchCount}: ' + str.substring(match.start, match.end));print('Starting index of Match ${matchCount} in input string: ${match.start}');print('Index after ending index of Match ${matchCount} in input string: ${match.end}');print('Number of captured groups in Match ${matchCount}: ${match.groupCount}');print('Input string: ${match.input}');print('Pattern used to search for Match ${matchCount}: ${match.pattern}');print('String matched by group 1: ${match.group(1)}\n');});}
Free Resources