Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]", "");
like image 577
Zbarcea Christian Avatar asked Jun 14 '26 21:06

Zbarcea Christian


1 Answers

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.

like image 195
Lucas Trzesniewski Avatar answered Jun 17 '26 12:06

Lucas Trzesniewski