Andres Acosta
Andres Acosta

Reputation: 113

How to remove more than one match in Java using replaceAll()?

Hi there I am trying to remove two or more words in a String with the replaceAll method in Java but I am not good in regex at all and I have not been able to do it. So, here is the code:

    public static void main(String[] args) {
    String s= "@class::menu-select @id::calibration-content";
    System.out.println(s.replaceAll("[(@class::)(@id::)]",""));
}

But when I run this what I get is the following text menu-eet brton-ontent By the way the words I am trying to remove are @class:: and @id:: Does anyone know how to do this? Thanks in advance!

Upvotes: 1

Views: 135

Answers (3)

James Mudd
James Mudd

Reputation: 2383

This code should work

public static void main(String[] args) {
    String s= "@class::menu-select @id::calibration-content";
    System.out.println(s.replaceAll("@class::|@id::", ""));
}

It prints

menu-select calibration-content

Upvotes: 1

Jacob G.
Jacob G.

Reputation: 29710

String#replaceAll accepts a regular expression, and you're passing it a character class of substrings you're looking to replace, which isn't correct.

Instead, you could change the regular expression to look specifically for the substrings:

System.out.println(s.replaceAll("@class::|@id::",""));

This results in the following output:

menu-select calibration-content

Keep in mind that there are more efficient methods of removing substrings from a String than regex.

Upvotes: 2

DuncG
DuncG

Reputation: 15176

The expression you used contains [] which matches on the range of characters inbetween. Just use something like:

System.out.println(s.replaceAll("@(class|id)::",""));

Upvotes: 1

Related Questions