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
| Parameter | Optional/Required | Description |
|---|---|---|
source | required | The pattern string for the regular expression. |
multiLine | optional | Specifies whether the pattern should match across line breaks. Default is false. |
caseSensitive | optional | Specifies whether the pattern should be case sensitive. Default is true. |
unicode | optional | Specifies whether to use Unicode matching. Default is false. |
dotAll | optional | Specifies whether dot matches all characters including line breaks. Default is false. |
✐ Examples
1 Matching a specific word
In this example,
- We create a `RegExp` object named `pattern` with the pattern 'hello'.
- We check if the pattern matches the string 'hello world' using the `hasMatch()` method.
- 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,
- We create a `RegExp` object named `pattern` with the pattern '[0-9]+' to match one or more digits.
- We check if the pattern matches the string '123' using the `hasMatch()` method.
- 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,
- We create a `RegExp` object named `pattern` with the raw pattern '\w+' to match one or more word characters.
- We check if the pattern matches the string 'hello' using the `hasMatch()` method.
- 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.