Dart RegExp()
Syntax & Examples


RegExp constructor

The `RegExp` constructor in Dart creates a regular expression object.


Syntax of RegExp

The syntax of RegExp.RegExp constructor is:

RegExp(String source, { bool multiLine: false bool caseSensitive: true @Since("2.4") bool unicode: false @Since("2.4") bool dotAll: false })

This RegExp constructor of RegExp constructs a regular expression.

Parameters

ParameterOptional/RequiredDescription
sourcerequiredThe pattern string for the regular expression.
multiLineoptionalSpecifies whether the pattern should match across line breaks. Default is false.
caseSensitiveoptionalSpecifies whether the pattern should be case sensitive. Default is true.
unicodeoptionalSpecifies whether to use Unicode matching. Default is false.
dotAlloptionalSpecifies whether dot matches all characters including line breaks. Default is false.


✐ Examples

1 Matching a specific word

In this example,

  1. We create a `RegExp` object named `pattern` with the pattern 'hello'.
  2. We check if the pattern matches the string 'hello world' using the `hasMatch()` method.
  3. We print the result, which should be true.

Dart Program

void main() {
  RegExp pattern = RegExp('hello');
  print(pattern.hasMatch('hello world'));
}

Output

true

2 Matching digits

In this example,

  1. We create a `RegExp` object named `pattern` with the pattern '[0-9]+' to match one or more digits.
  2. We check if the pattern matches the string '123' using the `hasMatch()` method.
  3. We print the result, which should be true.

Dart Program

void main() {
  RegExp pattern = RegExp('[0-9]+');
  print(pattern.hasMatch('123'));
}

Output

true

3 Matching word characters

In this example,

  1. We create a `RegExp` object named `pattern` with the raw pattern '\w+' to match one or more word characters.
  2. We check if the pattern matches the string 'hello' using the `hasMatch()` method.
  3. We print the result, which should be true.

Dart Program

void main() {
  RegExp pattern = RegExp(r'\w+');
  print(pattern.hasMatch('hello'));
}

Output

true

Summary

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