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]", "");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With