How to Get String Between Two Tags in Java

In this tutorial, we are going to see how to get string between two tags in Java. Regular Expressions or Regex is an API for defining patterns that can be used to find, manipulate, and edit a string in Java. Regex is widely used to define constraints. Regular expressions are provided under java.util package.

  • (. +?) means any character between the two specified tags.
  • DOTALL is a member of Pattern class activates “dotall” mode. By default, the ”.”(dot) In regular expressions matches all characters except line breaks. That is, when you use DOTALL as a flag value for the compile() method, the ”.”(dot) Matches all characters, including line breaks.

Java Program to Get String Between Two Tags:
import java.util.regex.*;

public class Main 
  public static void main(String[]args) 
      Pattern p = Pattern.compile("<b>(.+?)</b>", Pattern.DOTALL);
      Matcher m = p.matcher("<b>String I want to extract</b>");


String I want to extract
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *