在其他匹配内查找匹配 Java 正则表达式
要在另一个匹配内匹配模式,你需要编译以匹配外部模式的正则表达式,找到匹配项,检索结果并将结果作为输入传递给内部匹配器对象。
示例
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+"; //Creating a pattern object Pattern patternOuter = Pattern.compile(regexOuter); Pattern patternInner = Pattern.compile(regexInner); //Matching the compiled pattern in the String 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
广告