将字符串转换为电话号码Ruby

时间:2016-05-27 13:30:33

标签: ruby string phone-number

我使用Ruby。 我想将字符串转换为格式化电话号码。

示例:

  • 如果字符串有10个字符:'0123456789' - >它转换为'0123-45-6789'
  • 如果字符串有11个字符:'01234567899' - >它转换为'0123-456-7899'

4 个答案:

答案 0 :(得分:2)

如果您正在使用Rails项目,那么有一个内置的视图助手可以为您完成大部分的工作:http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_phone

number_to_phone(5551234)                                     # => 555-1234
number_to_phone("5551234")                                   # => 555-1234
number_to_phone(1235551234)                                  # => 123-555-1234
number_to_phone(1235551234, area_code: true)                 # => (123) 555-1234
number_to_phone(1235551234, delimiter: " ")                  # => 123 555 1234
number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
number_to_phone(1235551234, country_code: 1)                 # => +1-123-555-1234
number_to_phone("123a456")                                   # => 123a456
number_to_phone("1234a567", raise: true)                     # => InvalidNumberError

所以,在你的情况下:

number_to_phone('0123456789') # => '0123-45-6789'
number_to_phone('01234567899') # => '0123-456-7899'

答案 1 :(得分:1)

'0123456789'.gsub(/^(\d{4})(\d+)(\d{4})$/, '\1-\2-\3')
# => "0123-45-6789" 
'01234567899'.gsub(/^(\d{4})(\d+)(\d{4})$/, '\1-\2-\3')
# => "0123-456-7899" 

答案 2 :(得分:1)

纯Ruby方式,尝试String#insert

> "0123456789".insert(4, '-').insert(-5, '-')
#=> "0123-45-6789" 
> "01234567899".insert(4, '-').insert(-5, '-')
#=> "0123-456-7899" 

注意:负数表示您从字符串的末尾开始计数,而正数表示您从字符串的开头开始计算

答案 3 :(得分:0)

R = /
    (?<=\A\d{4}) # match four digits at beginning of string in positive lookbehind
    |            # or
    (?=\d{4}\z)  # match four digits at end of string in positive lookahead
    /x           # free-spacing regex definition mode

def break_it(str)
  str.split(R).join('-')
end

break_it '0123456789'
  #=> "0123-45-6789" 
break_it '01234567899' 
  #=> "0123-456-7899" 

我会推荐这个吗?不,我更喜欢@Gagan的解决方案,如果没有采取,我会提供。我提出这个解决方案是为了普遍感兴趣。