正则表达式(Dart)课题
1. 使⽤正则表达式匹配字符串
使⽤正则表达式 "\d{3}-(\d{4})-\d{2}" 匹配字符串 "123-4567-89"
返回匹配结果:’"123-4567-89" 以及 "4567"
2. 使⽤正则表达式替换字符串(模式)
使⽤正则表达式 "(\d+)-(\d+)-(\d+)" 匹配字符串 "123-4567-89"
使⽤模式字符串 "$3-$1-$2" 替换匹配结果,返回结果 "89-123-4567"。
3. 使⽤正则表达式替换字符串(回调)
使⽤正则表达式 "\d+" 匹配字符串 "123-4567-89"
将匹配结果即三个数字串全部翻转过来,返回结果 "321-7654-98"。
4. 使⽤正则表达式分割字符串
使⽤正则表达式 "%(begin|next|end)%" 分割字符串"%begin%hello%next%world%end%"
返回正则表达式分隔符之间的两个字符串 "hello" 和 "world"。
Dart
void main() {
final s = "123-4567-89,987-6543-21";
final r = RegExp(r"\d{3}-(\d{4})-\d{2}");
final m = r.firstMatch(s);
if (m != null) print("Found matches:");
final ms = r.allMatches(s);
for (var j = 0; j <= m.groupCount; j++)
print("group $i,$j : ${m.group(j)}");
});
placeAllMapped(RegExp(r"(\d+)-(\d+)-(\d+)"),
(m) => r"$3-$1-$2".replaceAllMapped(RegExp(r"\$(\d)"),
正则匹配空字符串(m2) => m.group(int.up(1))))));
// stackoverflow/questions/21521729/how-do-i-reverse-a-string-in-dart
placeAllMapped(RegExp(r"\d+"), (m) => m.group(0).split("").reversed.join()));
print("%begin%hello%next%world%end%".split(RegExp("%(begin|next|end)%")));
}
/*
Found matches:
group 0,0 : 123-4567-89
group 0,1 : 4567
group 1,0 : 987-6543-21
group 1,1 : 6543
89-123-4567,21-987-6543
321-7654-98,789-3456-12
[, hello, world, ]
*/
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论