[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 @ 2021-02-15 18:03  漫游者杰特  阅读(452)  评论(0编辑  收藏  举报