要在另一个匹配项中匹配模式,您需要编译正则表达式以匹配外部模式,找到匹配项以检索结果并将结果作为输入传递给内部Matcher对象。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherExample { public static void main(String[] args) { int start = 0, len = -1; Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regexOuter = "<b>(.*?)</b>"; String regexInner = "\\d+"; //创建一个模式对象 Pattern patternOuter = Pattern.compile(regexOuter); Pattern patternInner = Pattern.compile(regexInner); //匹配字符串中的已编译模式 Matcher outerMatcher = patternOuter.matcher(input); while (outerMatcher.find()) { Matcher innerMatcher = patternInner.matcher(outerMatcher.group(1)); while(innerMatcher.find()){ System.out.println(innerMatcher.group()); } } } }
输出结果
Enter input text: This is sample HTML data 123 sample text hello 123