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
Parameter | Optional/Required | Description |
---|---|---|
input | required | The input string on which to search for matches. |
start | optional | The 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,
- We create a regular expression `regex` to match words.
- We define a text string `text`.
- We use the `allMatches` method to find all matches of the regex in the text.
- 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,
- We create a regular expression `regex` to match numbers.
- We define a text string `text`.
- We use the `allMatches` method to find all matches of the regex in the text.
- 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,
- We create a regular expression `regex` to match proper nouns (words starting with an uppercase letter followed by lowercase letters).
- We define a text string `text`.
- We use the `allMatches` method to find all matches of the regex in the text.
- 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.