public static void main(String[] args) {
String content = "在一些字里面放进去高中这两个字";
// Matcher matcher = Pattern.compile("高中").matcher(content);
while (Pattern.compile("高中").matcher(content).find()) {
System.out.println(Pattern.compile("高中").matcher(content).group());
}
}
这样会报错:
Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:536)
at java.util.regex.Matcher.group(Matcher.java:496)
at com.lawsdata.collie.instrument.valuegetter.LitigantDegreeGetter.main(LitigantDegreeGetter.java:49)
解决方法,用一个matcher对象来接收Pattern.compile("高中").matcher(content);然后通过matcher来find和group
public static void main(String[] args) { String content = "在一些字里面放进去高中这两个字"; Matcher matcher = Pattern.compile("高中").matcher(content); while (matcher.find()) { System.out.println(matcher.group()); } }
这样结果正确可以输出 高中