Reputation: 5857
I want to match all dollar sign words in the text. For example, "Hello $VARONE this is $VARTWO"
, would match $VARONE
and $VARTWO
.
The regex should be /\$(\w+)/g
but when I use this in Dart with the compiler in DartPad (https://dartpad.dartlang.org/) the words are not matched.
void main() {
final variableGroupRegex = new RegExp(r"/\$(\w+)/g");
Iterable<Match> matches = variableGroupRegex.allMatches("Hello \$VARONE this is \$VARTWO");
for (Match match in matches) {
print("match $match"); // code is never run as no matches
}
}
Upvotes: 1
Views: 1501
Reputation: 626738
You may fix it as
final variableGroupRegex = new RegExp(r"\$(\w+)");
Iterable<Match> matches = variableGroupRegex.allMatches("Hello \$VARONE this is \$VARTWO");
for (Match match in matches) {
print(match.group(0));
print(match.group(1));
}
Output:
$VARONE
VARONE
$VARTWO
VARTWO
Here, you define the regex with a raw string literal, and r"\$(\w+)
defines the \$(\w+)
pattern. Then, to access the whole match, you may use .group(0)
and to grab the captured value, use .group(1)
.
Upvotes: 3