What is the Match class in Dart?

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.

svg viewer

Implementation

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 digits
RegExp reg = new RegExp(r'(\d+)');
//Iterating over the matches returned from allMatches
Iterable allMatches = reg.allMatches(str);
var matchCount = 0;
allMatches.forEach((match) {
matchCount += 1;
print('Match ${matchCount}: ' + str.substring(match.start, match.end));
});
}

Class properties

The Match class includes several useful properties:

  • Match.startint: Returns the index of the string where the match starts.
  • Match.endint: Returns the index of the string one after where the match ends.
  • Match.groupCountint: Returns the total number of captured groups in the match.
  • Match.inputString: Returns the string on which pattern matching has been done.
  • Match.patternPattern: Returns the pattern used to search the input string.

Groups are substrings that were part of some pattern’s matchings.

Class methods

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.

Implementation

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 digits
RegExp reg = new RegExp(r'(\d+)');
//Iterating over the matches returned from allMatches
Iterable 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

Copyright ©2025 Educative, Inc. All rights reserved