Strings
RegExp Basics
RegExp(pattern) compiles a regular expression from a string. Three common entry points cover most learner cases: hasMatch(text) returns a bool that answers whether the pattern hits anywhere, firstMatch(text) returns the first Match (or null) and m.group(0) reads the whole match, and allMatches(text) returns every match as an Iterable<Match> that can be transformed with the usual map/join.
Program
Play the program to compile r'b\w+', check that it matches cat bat bird, read the first hit, and join every hit with a comma.
regex_basics.dart
Replay: real traced execution (multi-file project)
void main() {
var text = 'cat bat bird';
var pattern = r'b\w+';
var re = RegExp(pattern);
var ok = re.hasMatch(text);
var first = re.firstMatch(text)!.group(0);
var all = re.allMatches(text).map((m) => m.group(0)).join(',');
print('$ok $first $all');
}
text ← cat bat bird
1void main() {2 var text = 'cat bat bird';3 var pattern = r'b\w+';values this stepcat bat birdtextpattern ← b\w+
2var text = 'cat bat bird';3var pattern = r'b\w+';4var re = RegExp(pattern);values this stepb\w+patternre ← RegExp(b\w+)
3var pattern = r'b\w+';4var re = RegExp(pattern);5var ok = re.hasMatch(text);values this stepRegExp(b\w+)reb\w+patternok ← true
4var re = RegExp(pattern);5var ok = re.hasMatch(text);6var first = re.firstMatch(text)!.group(0);values this steptrueokRegExp(b\w+)recat bat birdtextfirst ← bat
5var ok = re.hasMatch(text);6var first = re.firstMatch(text)!.group(0);7var all = re.allMatches(text).map((m) => m.group(0)).join(',');values this stepbatfirstRegExp(b\w+)recat bat birdtextall ← bat,bird
6var first = re.firstMatch(text)!.group(0);7var all = re.allMatches(text).map((m) => m.group(0)).join(',');8print('$ok $first $all');values this stepbat,birdallRegExp(b\w+)recat bat birdtextprint('$ok $first $all');
7 var all = re.allMatches(text).map((m) => m.group(0)).join(',');8 print('$ok $first $all');9}outputtrue bat bat,birdvalues this steptrueokbatfirstbat,birdall
Follow the Matches
textstarts ascat bat bird.- The pattern
b\w+looks for words that start withb. hasMatchis true because matches exist.- The first match is
bat. - All matches join as
bat,bird, so the output istrue bat bat,bird. | check | result | | --- | --- | | any match? | true | | first match | bat | | all matches | bat,bird |
RegExp
`RegExp(pattern)` compiles a regular expression from a string. A raw string `r'...'` keeps backslashes literal, so `b\w+` reads cleanly.
hasMatch and firstMatch
`re.hasMatch(text)` returns `bool`. `re.firstMatch(text)` returns the first `Match` (or `null`); `m.group(0)` is the whole match text.
allMatches
`re.allMatches(text)` returns every match as an `Iterable<Match>`, so `.map((m) => m.group(0)).join(',')` collects each hit into a comma-separated string.
Exercise: regex_basics.dart
Reproduce true bat bat,bird, then trace why b\\w+ first finds bat and then finds bat,bird as all matches.