Search code examples
javaregexreplaceall

Replace all content within braces?


In the end I need a regex which basically converts me a phone number into a E164 conform number. As for now i got this:

result = s.replaceAll("[(*)|+| ]", "");

It replaces everything fine: the spaces, the "+"-sign and also the braces "()". But it does not match the content of its braces, so that e.g. the number +49 (0)11 111 11 11 will be replaced to 49111111111.

How can I get this to work?


Solution

  • You can do it, but what if there's more than just a zero between parentheses?

    result = s.replaceAll("\\([^()]*\\)|[*+ ]+", "");
    

    As a verbose regex:

    result = s.replaceAll(
        "(?x)     # Allow comments in the regex.                     \n" +
        "\\(      # Either match a (                                 \n" +
        "[^()]*   # then any number of characters except parentheses \n" +
        "\\)      # then a ).                                        \n" +
        "|        # Or                                               \n" +
        "[*+\\ ]+ # Match one or more asterisks, pluses or spaces", "");