Search code examples
javaregexphone-number

Java string replace regex for invalid characters in a phone number


I'm trying to write a regex to replace all invalid characters in a phone number:

Example phone numbers:

  • +36 00 211 1111 -> +36002111111
  • +49 03 691 4193 -> +49036914193
  • +36 00 211 1111 -> +36002111111
  • 06 78 90 12 34 -> 0678901234

The regex should allow the "+" sign only if it's the first character in the string and the rest only numeric types [0-9]

This is my current regex:

phone = phone.replaceAll("[/(?<!^)\+|[^\d+]+//g]", "");

Solution

  • Use this one: [^\d+]|(?!^)\+

    phone = phone.replaceAll("[^\\d+]|(?!^)\\+", "");
    
    • [^\d+] matches a character that's not a digit or +
    • (?!^)\+ matches + characters that are not at the start of the string

    In your current regex, [/(?<!^)\+|[^\d+] is just a character class (so it matches a single character, and + makes it repeat that character class, and then your pattern matches the literal //g] string. So, bad syntax.