Dart String matchAsPrefix()
Syntax & Examples

Syntax of String.matchAsPrefix()

The syntax of String.matchAsPrefix() method is:

 Match? matchAsPrefix(String string, [int start = 0]) 

This matchAsPrefix() method of String matches this pattern against the start of string.

Parameters

ParameterOptional/RequiredDescription
stringrequiredthe string to match against the pattern
startoptional [default value is 0]the index to start matching from

Return Type

String.matchAsPrefix() returns value of type Match?.



✐ Examples

1 Find "world" at the start of the string

In this example,

  1. We create a string str with the value 'Hello, world!'.
  2. We create a regular expression pattern regex to match '[A-Z]ello'.
  3. We then use the matchAsPrefix() method to find a match starting from the beginning of the string.
  4. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  RegExp regex = RegExp(r'[A-Z]ello');
  Match? match1 = regex.matchAsPrefix(str);
  print('Match found: $match1');
}

Output

Match found: Instance of '_MatchImplementation'

2 Find 'D' at the start of the string

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We create a regular expression pattern regex to match 'D'.
  3. We then use the matchAsPrefix() method to find a match starting from the beginning of the string.
  4. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  RegExp regex = RegExp(r'D');
  Match? match2 = regex.matchAsPrefix(str);
  print('Match found: $match2');
}

Output

Match found: null

3 Find 'ipsum' at the start of the string

In this example,

  1. We create a string str with the value 'Lorem ipsum dolor sit amet'.
  2. We create a regular expression pattern regex to match 'Lorem'.
  3. We then use the matchAsPrefix() method to find a match starting from the beginning of the string.
  4. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  RegExp regex = RegExp(r'Lorem');
  Match? match3 = regex.matchAsPrefix(str);
  print('Match found: $match3');
}

Output

Match found: Instance of '_MatchImplementation'

Summary

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