Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gsub to remove illegal characters in phone number

Tags:

regex

ruby

gsub

I want to remove all characters in a string that do not belong in a phone number string. The first character may or may not be a "+" and all other characters must be digits.

I had gsub(/\D/, ''), but I want to keep the first character if it is a "+" (or a digit, of course). I then tried some negation, but this is not right, either: gsub(/^(\+?(\d))/, '').

How can I ignore the first character with regex iff it is a "+"?

like image 926
Eric Cochran Avatar asked Nov 23 '25 08:11

Eric Cochran


1 Answers

How about using a negative lookahead at the beginning:

gsub(/(?!^\+)\D*/, '')

Basically, the above regex should remove any series of non-digits where the first character is not a single '+' character at the beginning of the string.

Hope it helps.

like image 103
Lautaro Nahuel De León Avatar answered Nov 24 '25 23:11

Lautaro Nahuel De León



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!