我用Ruby。我想将字符串转换为格式化电话号码。
例:
- 如果字符串有 10 个字符:
"0123456789"应转换为"0123-45-6789"
- 如果字符串有 11 个字符:
"01234567899"应转换为"0123-456-7899"
纯 Ruby 方式,请尝试String#insert
> "0123456789".insert(4, '-').insert(-5, '-')
#=> "0123-45-6789"
> "01234567899".insert(4, '-').insert(-5, '-')
#=> "0123-456-7899"
备注:负数表示您从字符串的末尾计数,正数表示您从字符串的开头计数
如果你在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'
'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"
R = /(?<=A.{4})(.+)(?=.{4}z)/
def break_it(str)
str.sub(R, '-1-')
end
break_it '0123456789'
#=> "0123-45-6789"
break_it '01234567899'
#=> "0123-456-7899"
正则表达式可以细分如下。
(?<= # begin a positive lookbehind
A.{4} # match four chars at the beginning of the string
) # end positive lookbehind
(.+) # match one or more chars and save to capture group 1
(?= # begin a positive lookahead
.{4}z # match four chars at the end of the string
) # end positive lookahead
/