Dart RegExp allMatches()
Syntax & Examples

RegExp.allMatches() method

The `allMatches` method in Dart's `RegExp` class returns an iterable of matches of the regular expression on the specified input string.


Syntax of RegExp.allMatches()

The syntax of RegExp.allMatches() method is:

 Iterable<RegExpMatch> allMatches(String input, [ int start = 0 ]) 

This allMatches() method of RegExp returns an iterable of the matches of the regular expression on input.

Parameters

ParameterOptional/RequiredDescription
inputrequiredThe input string on which to search for matches.
startoptionalThe starting position in the input string from which to begin the search. The default is 0.

Return Type

RegExp.allMatches() returns value of type Iterable<RegExpMatch>.



✐ Examples

1 Matching Words

In this example,

  1. We create a regular expression `regex` to match words.
  2. We define a text string `text`.
  3. We use the `allMatches` method to find all matches of the regex in the text.
  4. We iterate over the matches and print each match.

Dart Program

void main() {
  RegExp regex = RegExp(r'\w+');
  String text = 'Hello World!';
  Iterable<RegExpMatch> matches = regex.allMatches(text);
  for (RegExpMatch match in matches) {
    print('Match: ${match.group(0)}');
  }
}

Output

Match: Hello
Match: World

2 Matching Numbers

In this example,

  1. We create a regular expression `regex` to match numbers.
  2. We define a text string `text`.
  3. We use the `allMatches` method to find all matches of the regex in the text.
  4. We iterate over the matches and print each match.

Dart Program

void main() {
  RegExp regex = RegExp(r'\d+');
  String text = 'Today is 25th December 2023';
  Iterable<RegExpMatch> matches = regex.allMatches(text);
  for (RegExpMatch match in matches) {
    print('Match: ${match.group(0)}');
  }
}

Output

Match: 25
Match: 2023

3 Matching Proper Nouns

In this example,

  1. We create a regular expression `regex` to match proper nouns (words starting with an uppercase letter followed by lowercase letters).
  2. We define a text string `text`.
  3. We use the `allMatches` method to find all matches of the regex in the text.
  4. We iterate over the matches and print each match.

Dart Program

void main() {
  RegExp regex = RegExp(r'[A-Z][a-z]+');
  String text = 'The quick Brown Fox jumps over the lazy Dog';
  Iterable<RegExpMatch> matches = regex.allMatches(text);
  for (RegExpMatch match in matches) {
    print('Match: ${match.group(0)}');
  }
}

Output

Match: The
Match: Brown
Match: Fox
Match: Dog

Summary

In this Dart tutorial, we learned about allMatches() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.