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

ParameterOptional/RequiredDescription
inputrequiredThe 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,

  1. We create a `RegExp` object named `pattern` with the pattern '\d+' to match one or more digits.
  2. We define a `text` string containing alphanumeric characters.
  3. We use the `firstMatch()` method to find the first digit sequence in the `text` string.
  4. 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,

  1. We create a `RegExp` object named `pattern` with the pattern 'hello'.
  2. We define a `text` string containing the phrase 'hello world'.
  3. We use the `firstMatch()` method to find the first occurrence of 'hello' in the `text` string.
  4. 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.