Dart String allMatches()
Syntax & Examples


Syntax of String.allMatches()

The syntax of String.allMatches() method is:

 Iterable<Match> allMatches(String string, [int start = 0]) 

This allMatches() method of String matches this pattern against the string repeatedly.

Parameters

ParameterOptional/RequiredDescription
stringrequiredmatching is done against this string
startoptional [default value is 0]if provided, matching will start at this index

Return Type

String.allMatches() returns value of type Iterable<Match>.



✐ Examples

1 Match all numbers in the string

In this example,

  1. We create a regular expression regex to match one or more digits.
  2. We then use the allMatches() method with the string 'Today is 2024-05-02 and 42 is the answer.'
  3. Iterating over the matches, we print each match found.

Dart Program

void main() {
  RegExp regex = RegExp(r'\d+');
  Iterable<Match> matches = regex.allMatches('Today is 2024-05-02 and 42 is the answer.');
  for (Match match in matches) {
    print('Match found: ${match.group(0)}');
  }
}

Output

Match found: 2024
Match found: 05
Match found: 02
Match found: 42

2 Match all letters in the string

In this example,

  1. We create a regular expression regex to match any alphabet character.
  2. We then use the allMatches() method with the string 'Hello World!'
  3. Iterating over the matches, we print each match found.

Dart Program

void main() {
  RegExp regex = RegExp(r'[A-Za-z]');
  Iterable<Match> matches = regex.allMatches('Hello World!');
  for (Match match in matches) {
    print('Match found: ${match.group(0)}');
  }
}

Output

Match found: H
Match found: e
Match found: l
Match found: l
Match found: o
Match found: W
Match found: o
Match found: r
Match found: l
Match found: d

3 Match all words in the string

In this example,

  1. We create a regular expression regex to match one or more alphabetic characters.
  2. We then use the allMatches() method with the string 'The quick brown fox jumps over the lazy dog.'
  3. Iterating over the matches, we print each match found.

Dart Program

void main() {
  RegExp regex = RegExp(r'[a-zA-Z]+');
  Iterable<Match> matches = regex.allMatches('The quick brown fox jumps over the lazy dog.');
  for (Match match in matches) {
    print('Match found: ${match.group(0)}');
  }
}

Output

Match found: The
Match found: quick
Match found: brown
Match found: fox
Match found: jumps
Match found: over
Match found: the
Match found: lazy
Match found: dog

Summary

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