R = /
\d{2,3} # match 2 or 3 digits (greedily)
(?= # begin positive lookahead
\d{2,3} # match 2 or 3 digits
| # or
\z # match the end of the string
) # end positive lookahead
/x # free-spacing regex definition mode
Условно написано
R = /\d{2,3}(?=\d{2,3}|\z)/
def doit(str)
s = str.gsub(/\D/,'')
return s if s.size < 4
s.scan(R).join('-')
end
doit "555 123 123"
#=> "555-123-123"
doit "555 123 1234"
#=> "555-123-12-34"
doit "555 123 12345"
#=> "555-123-123-45"
doit "(+1) 888 33x19"
#=> "188-833-19"
doit "123"
#=> "123"
doit "1234"
#=> "12-34"