Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Hi there I’am tryinig to remove two o 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
BTW the words I am trying to remove are @class:: and @id::
Does anyone knows how to do this ? ¡Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading