I use Ruby. I want to convert string to format phone number.
Example:
- If string have 10 character:
'0123456789' should convert to '0123-45-6789'
- If string have 11 character:
'01234567899' should convert to '0123-456-7899'
I use Ruby. I want to convert string to format phone number.
Example:
'0123456789' should convert to '0123-45-6789'
'01234567899' should convert to '0123-456-7899'
Pure Ruby way, try String#insert
> "0123456789".insert(4, '-').insert(-5, '-')
#=> "0123-45-6789"
> "01234567899".insert(4, '-').insert(-5, '-')
#=> "0123-456-7899"
Note: The negative numbers mean that you are counting from the end of the string and positive number means that you are counting from the beginning of the string
If you are working in a Rails project then there is a built-in view helper which can do most of the leg-work for you: 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
So, in your case:
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"
The regular expression can be broken down as follows.
(?<= # 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
/