RegExp
- Dart course
- Beginner
- Lesson 91/116
- 5 min
Learn regular expressions with RegExp.
What is RegExp?
RegExp is the Dart class for regular expressions. It searches text for a pattern, such as digits, letters or a specific shape. RegExp(r"\d+") matches one or more digits. The leading r marks a raw string; backslashes are not treated as escapes.
To test the pattern use hasMatch; it returns true or false. RegExp(r"\d").hasMatch("a3") gives true. For the first match use firstMatch, for all matches allMatches. Powerful for validation, parsing and filtering.
hasMatch and firstMatch
hasMatch returns only true or false; it does not know where the match is. It just answers the question "is there one?". Ideal for validating phone numbers, emails or postal codes.
If you need the match itself you use firstMatch; it returns a Match object or null if nothing matches. From a Match you get .group(0) for the whole match and .start for the starting index. For multiple matches allMatches returns an iterator you can loop over.
Practice Your turn: digit check with RegExp
Test a string for at least one digit with RegExp(r"\d"). Query "order 42" with hasMatch and print the result.
Starter code
void main() {
// Create a digit pattern
// Call hasMatch on "order 42" and print
}Sample solution
void main() {
final pattern = RegExp(r"\d");
print(pattern.hasMatch("order 42"));
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match RegExp patterns
| Term | Meaning |
|---|---|
\d+ |
one or more digits |
[a-z] |
lowercase letter |
^apple |
string starts with apple |
pear$ |
string ends with pear |
2 Which method tests that a string has at least one digit?
final r = RegExp(r"\d");
final v = r._____(s);- firstMatch
- hasMatch
- allMatches
- stringMatch Correct answer
Explanation: hasMatch returns true/false.
3 The RegExp pattern
final digits = ____r"\d+");
final digits = RegExp(r"\d+");
Explanation: The RegExp class builds the pattern.