Dart RegExp firstMatch()
Syntax & Examples
RegExp.firstMatch() method
The `firstMatch` method in Dart's `RegExp` class searches for the first match of the regular expression in a given input string.
Syntax of RegExp.firstMatch()
The syntax of RegExp.firstMatch() method is:
RegExpMatch firstMatch(String input)
This firstMatch() method of RegExp searches for the first match of the regular expression in the string input
. Returns null
if there is no match.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
input | required | The input string in which to search for the first match. |
Return Type
RegExp.firstMatch() returns value of type RegExpMatch
.
✐ Examples
1 Finding the first digit sequence
In this example,
- We create a `RegExp` object named `pattern` with the pattern '\d+' to match one or more digits.
- We define a `text` string containing alphanumeric characters.
- We use the `firstMatch()` method to find the first digit sequence in the `text` string.
- If a match is found, we print the first match using `match.group(0)`; otherwise, we print 'No match found.'
Dart Program
void main() {
RegExp pattern = RegExp(r'\d+');
String text = '123 abc 456 def';
RegExpMatch? match = pattern.firstMatch(text);
if (match != null) {
print('First match: ${match.group(0)}');
} else {
print('No match found.');
}
}
Output
First match: 123
2 Finding the first occurrence of 'hello'
In this example,
- We create a `RegExp` object named `pattern` with the pattern 'hello'.
- We define a `text` string containing the phrase 'hello world'.
- We use the `firstMatch()` method to find the first occurrence of 'hello' in the `text` string.
- If a match is found, we print the matched substring using `match.group(0)`; otherwise, we print 'No match found.'
Dart Program
void main() {
RegExp pattern = RegExp('hello');
String text = 'hello world';
RegExpMatch? match = pattern.firstMatch(text);
if (match != null) {
print('First match: ${match.group(0)}');
} else {
print('No match found.');
}
}
Output
First match: hello
Summary
In this Dart tutorial, we learned about firstMatch() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.