使用Ruby gsub删除电话号码中的非法字符

时间:2021-12-16 06:28:38

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))/, '').

我有gsub(/\D/,”),但如果第一个字符是“+”(当然是数字),我想保留它。然后我试过否定,但这是不正确的,要么:gsub(/ ^ \ + ?(\ d)/,”)。

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

我怎么可以忽略第一个字符的regex iff它是一个“+”?

2 个解决方案

#1


5  

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.

基本上,上面的regex应该删除任何系列的非数字,其中第一个字符不是字符串开头的单个“+”字符。

Hope it helps.

希望它可以帮助。

#2


0  

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:

除非你必须在一个gsub中完成它,否则把加号单独拉出来可能会更简单。您可以使用[]方法,例如:

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

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.

to_s是必需的,因为如果没有找到加号,方法将返回nil。

#1


5  

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.

基本上,上面的regex应该删除任何系列的非数字,其中第一个字符不是字符串开头的单个“+”字符。

Hope it helps.

希望它可以帮助。

#2


0  

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:

除非你必须在一个gsub中完成它,否则把加号单独拉出来可能会更简单。您可以使用[]方法,例如:

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

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.

to_s是必需的,因为如果没有找到加号,方法将返回nil。