在我们开发过程中我们经常使用正则表达式来进行字符串的匹配,本文我们就来介绍Dart中正则表达式的使用。
要使用正则表达式是,我们需要用到RegExp
类。
匹配-验证手机号
RegExp exp = RegExp(
r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
bool matched = exp.hasMatch(mobileTextController.text);
查找所有匹配结果
除了验证匹配之外,我们还可以查找所有的匹配,比如我们查找句子中的所有单词:
RegExp exp = new RegExp(r"(\w+)");
String str = "This is Lloyd's blog";
Iterable<Match> matches = exp.allMatches(str);
for (Match m in matches) {
String match = m.group(0);
print(match);
}
输出:
This
is
Lloyd
s
blog
总结
本文我们举例说明了在Dart中使用正则表达式的一些常用操作,如果需要更深入的研究,可以点击这里参考官方文档。
网友评论