简体   繁体   中英

Ruby gsub to remove illegal characters in phone number

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 "+"?

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.

Unless you absolutely have to do it in one gsub , it might be simpler to pull the plus sign out separately. You could use the [] method , with something like:

my_string[/^\\+/].to_s + my_string.gsub(/\\D/, '')

The to_s is necessary since the method will return nil if the plus sign isn't found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM