Categories
Java

Extract text between two strings with Java regex

Java is a general purpose language that has a library for almost anything. Using the Java Regex library, you can easily extract the text between two predefined strings. To extract the text between two strings tag1 and tag2 from the string content, we only need 4 lines of code:

String pattern = "(?<=tag1).*(?=tag2)";
Matcher matcher = Pattern.compile(pattern).matcher(content);
matcher.find();
String extracted = matcher.group(0);

You can print the variable extracted in a main:

package com;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String content = "blablatag1extract me !tag2 blalalalala";
        
        String pattern = "(?<=tag1).*(?=tag2)";
        Matcher matcher = Pattern.compile(pattern).matcher(content);
        matcher.find();
        String extracted = matcher.group(0);
        
        System.out.println(extracted);
    }
}

When you execute the code above, you will get the following result in the console:

extract me !

That’s it for this tutorial ! Please leave us a reply below if you have any question. We reply within 24 hours.

Leave a Reply

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