[Dart语法]第九章:正则表达式

正则表达式

[正则]匹配字符allMatches()、stringMatch()、hasMatch()、firstMatch()、matchAsPrefix()
//hasMatch()	是否匹配到,能匹配到返回true,否则返回false
//bool hasMatch(String input)
RegExp re = RegExp(r'(\w+)');
String str1 = "one two three";
print('Has match: ${re.hasMatch(str1)}');// Has match: true
//firstMatch()   第一匹配,匹配到第一个符合正则的值
//RegExpMatch firstMatch(String input)
Match firstMatch = re.firstMatch(str1);
print('First match: ${str1.substring(firstMatch.start, firstMatch.end)}');//First match: one


//allMatches()			全部匹配,类似Python的findAll
//Iterable<RegExpMatch> allMatches(String input, [int start])
var numbers = RegExp(r'\d+');//定义pattern,匹配数字正则
var someDigits = 'llamas live 15 to 20 years';
for (var match in numbers.allMatches(someDigits)) {
    print(match.group(0)); // 15 20
}

//stringMatch()			匹配第一个字符串
//String stringMatch(String input)
String str1 = "abcde qwerty";
RegExp re = RegExp(r'(\w+)');
String str1Match = re.stringMatch(str1);
print('Match str1: $str1Match');	//Match str1: abcde

//matchAsPrefix()		开头匹配,开头的值能匹配到返回true,否则false
//Match matchAsPrefix(String string, [int start])
String str1 = "abcde";
RegExp re = RegExp(r'abc');
Match str1Match = re.matchAsPrefix(str1);
print('Match str1: ${str1Match != null}'); //Match str1: true

posted @   漫游者杰特  阅读(466)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示