Search code examples
javaandroidregexreplaceall

ReplaceAll String java regex


I have a string that contains the following:

"Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)"

I want to replaceAll so I get rid of the brackets containing percentages but not the other numbers like so:

"Hello my name is and bye also C9, B6"

Currently I have this but it removes all my numbers, Any idea how I could fix it:

.replaceAll("[\\([0-9]\\%)]","");

Solution

  • Something like this maybe?

    "Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)".replaceAll("\\((?:\\d|\\.)+%\\)", "")
    

    Demo

    This here also deletes a single whitespace after each parenthesized percentage:

    "Hello my name is (0.9%) and (15%) bye (10.5%) also (C9, B6)".replaceAll("\\((?:\\d|\\.)+%\\) ", "")
    

    Gives:

    Hello my name is and bye also (C9, B6)