Dart RegExp hasMatch()
Syntax & Examples

RegExp.hasMatch() method

The `hasMatch` method in Dart's `RegExp` class checks whether the regular expression has a match in the specified input string.


Syntax of RegExp.hasMatch()

The syntax of RegExp.hasMatch() method is:

 bool hasMatch(String input) 

This hasMatch() method of RegExp returns whether the regular expression has a match in the string input.

Parameters

ParameterOptional/RequiredDescription
inputrequiredThe input string to search for a match.

Return Type

RegExp.hasMatch() returns value of type bool.



✐ Examples

1 Matching Numbers

In this example,

  1. We create a regular expression `regex` to match numbers.
  2. We define a text string `text`.
  3. We use the `hasMatch` method to check if the regex has a match in the text.
  4. We print the result.

Dart Program

void main() {
  RegExp regex = RegExp(r'\d+');
  String text = 'Today is 25th December 2023';
  bool hasMatch = regex.hasMatch(text);
  print('Regex has match: $hasMatch');
}

Output

Regex has match: true

2 Matching Proper Nouns

In this example,

  1. We create a regular expression `regex` to match proper nouns (words starting with an uppercase letter followed by lowercase letters).
  2. We define a text string `text`.
  3. We use the `hasMatch` method to check if the regex has a match in the text.
  4. We print the result.

Dart Program

void main() {
  RegExp regex = RegExp(r'[A-Z][a-z]+');
  String text = 'The quick Brown Fox jumps over the lazy Dog';
  bool hasMatch = regex.hasMatch(text);
  print('Regex has match: $hasMatch');
}

Output

Regex has match: true

3 Matching Non-Word Characters

In this example,

  1. We create a regular expression `regex` to match non-word characters.
  2. We define a text string `text`.
  3. We use the `hasMatch` method to check if the regex has a match in the text.
  4. We print the result.

Dart Program

void main() {
  RegExp regex = RegExp(r'\W+');
  String text = 'Hello World!';
  bool hasMatch = regex.hasMatch(text);
  print('Regex has match: $hasMatch');
}

Output

Regex has match: true

Summary

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