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("------------------------------");
}
}
}
运行结果: