Reputation: 9548
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
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
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 stringIn 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