Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
regex
string
communitycreator

What is RegExUtils.removeFirst in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

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.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

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;

Syntax

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

Parameters

  • 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.

Example

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")));
}
}

RELATED TAGS

java
regex
string
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring