java中匹配字符串,使用工具类regex包中的类与方法:
代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainDemo {
public static void main(String[] args) {
String str = "helloworld1234world5678";
String regStr = "\\d{4}";
String ipReg = "";
Pattern p = Pattern.compile(regStr);
Matcher m = p.matcher(str);
while(m.find()){
System.out.println("在str中匹配到的子字符串的起始索引="+m.start());
System.out.println("在str中匹配到的子字符串的结尾索引="+m.end());
System.out.println("匹配到的子字符串的值="+m.group());
System.out.println("------------------------------");
}
}
}
运行结果:

本文介绍了一个Java程序示例,演示如何使用正则表达式从字符串中匹配四位数字序列,并展示如何获取匹配到的内容及其在字符串中的位置。

被折叠的 条评论
为什么被折叠?



