Zbarcea Christian
Zbarcea Christian

Reputation: 9548

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:

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]", "");

Upvotes: 2

Views: 2815

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627145

The result can be achieved with a regex without any lookarounds. Capture the plus at the start of the string to be reinserted with $1 backreference in the replacement pattern and just match all non digits.

^(\+)|\D+

In Java:

.replaceAll("^(\\+)|\\D+", "$1")

Pattern details:

  • ^(\+) - group 1 capturing a literal plus at the start of the string
  • \D+ - one or more chars other than digits.

Upvotes: 2

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51400

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.

Upvotes: 10

Related Questions