Dart RegExp stringMatch()
Syntax & Examples


RegExp.stringMatch() method

The `stringMatch` method in Dart's `RegExp` class returns the first substring match of the regular expression in a given input string.


Syntax of RegExp.stringMatch()

The syntax of RegExp.stringMatch() method is:

 String stringMatch(String input) 

This stringMatch() method of RegExp returns the first substring match of this regular expression in input.

Parameters

ParameterOptional/RequiredDescription
inputrequiredThe input string in which to search for the first substring match.

Return Type

RegExp.stringMatch() returns value of type String.



✐ 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 `stringMatch()` method to find the first digit sequence in the `text` string.
  4. If a match is found, we print the matched substring; otherwise, we print 'No match found.'

Dart Program

void main() {
  RegExp pattern = RegExp(r'\d+');
  String text = '123 abc 456 def';
  String? match = pattern.stringMatch(text);
  if (match != null) {
    print('First match: $match');
  } 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 `stringMatch()` method to find the first occurrence of 'hello' in the `text` string.
  4. If a match is found, we print the matched substring; otherwise, we print 'No match found.'

Dart Program

void main() {
  RegExp pattern = RegExp('hello');
  String text = 'hello world';
  String? match = pattern.stringMatch(text);
  if (match != null) {
    print('First match: $match');
  } else {
    print('No match found.');
  }
}

Output

First match: hello

Summary

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