a shot of dev knowledge


What is RegExUtils.removeFirst in Java?


removeFirst is a static method of the RegExUtils that is used to remove only the first substring in a given string that matches the specified regular expression. Here, removing means replacing the substring with an empty string.

RegExUtils is defined in the Apache Commons Lang package. To add the Apache Commons Lang to the Maven project, add the following dependency to pom.xml file.


For other versions of the commons-lang package, refer to the Maven Repository.

RegExUtils class can be imported as follows.

import org.apache.commons.lang3.RegExUtils;


public static String removeFirst(final String text, final Pattern regex)


  • final String text: The string on which the regex is applied.
  • final Pattern regex: Regular expression.

Return value

This method returns the modified text after the first substring that matches the regex is removed.


In the code below, we define a text that has the word educative repeated multiple times. Next, we remove only the first occurrence of the word educative from the text through the removeFirst method.

The output of the code when executed would be the text without the first occurrence of the word educative.

import org.apache.commons.lang3.RegExUtils;

import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args)
        String text = "educative is the best platform for java. educative is the best platform for python. educative is the best platform for c.";
        System.out.println(RegExUtils.removeFirst(text, Pattern.compile("educative")));



View all Courses

Keep Exploring