Finding a Match Within Another Match Java regular expressions

To match a pattern within another match you need to compile the regular expression to match the outer pattern find the match retrieve the results and pass the results as input to the inner Matcher object.


 Live Demo

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.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(;


Enter input text:
This is sample HTML data 123 sample text hello