gpt4 book ai didi

regex - 在Dart正则表达式中匹配$(美元符号)词

转载 作者:行者123 更新时间:2023-12-03 03:17:53 36 4
gpt4 key购买 nike

我要匹配文本中的所有美元符号单词。例如,"Hello $VARONE this is $VARTWO"可以匹配$VARONE$VARTWO

正则表达式应该是/\$(\w+)/g,但是当我在Dart中将它与DartPad(https://dartpad.dartlang.org/)中的编译器一起使用时,单词不匹配。

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
}
}

最佳答案

您可以将其修复为

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));
}

输出:
$VARONE
VARONE
$VARTWO
VARTWO

在这里,您使用原始字符串文字定义了正则表达式,并且 r"\$(\w+)定义了 \$(\w+)模式。然后,要访问整个匹配项,可以使用 .group(0),并使用 .group(1)来获取捕获的值。

关于regex - 在Dart正则表达式中匹配$(美元符号)词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100622/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com