java代码如何使用正则表达式中模式检测指定字符串是第n次出现的相关说明
下文笔者讲述使用正则表达式匹配字符串是第几次出现的方法分享,如下所示
匹配字符串出现的次数
实现思路:
使用正则表达式的matcher方法
然后使用find即可匹配除具体的出现次数
如:
MatchResult findNthOccurance(int n, Pattern p, CharSequence src){
Matcher m = p.matcher(src);
for(int i = 0; i<n; i++) m.find();
return m;
}
例:匹配字符串出现的次数
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main(String args[]){
//按指定模式在字符串查找
Stringline="www.java265.com98232dsssd";
Stringpattern="(\D*)(\d+)(.*)";
//创建Pattern对象
Patternr=Pattern.compile(pattern);
//现在创建matcher对象
Matcherm=r.matcher(line);
if(m.find()){
System.out.println("发现值:"+m.group(0));
System.out.println("发现值:"+m.group(1));
System.out.println("发现值:"+m.group(2));
System.out.println("发现值:"+m.group(3));
}else{
System.out.println("未匹配值");
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


