The `firstMatch` method in Dart's `RegExp` class searches for the first match of the regular expression in a given input string.
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.
Parameter | Optional/Required | Description |
---|---|---|
input | required | The input string in which to search for the first match. |
RegExp.firstMatch() returns value of type RegExpMatch
.
In this example,
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.');
}
}
First match: 123
In this example,
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.');
}
}
First match: hello
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.