我刚开始学习正则表达式。我的代码有效,但我想让它更好。
# Ensure all of the Social Security numbers use dashes for delimiters.
# Example: 480.01.4430 and 480014430 would both be 480-01-4430.
def format_ssns(string)
string.gsub!(/\./, '-') if string =~ /(\d{9})|(\d{3})\D(\d{2})\D(\d{4})/
string.insert(3, '-') if string =~ /(\d{9})/
string.insert(6, '-') if string =~ /(\d{3})\D(\d{6})/
p string
end
format_ssns("234601422, 350.80.0744, 013-60-8762")
答案 0 :(得分:3)
这涵盖所有3:
string = "234601422, 350.80.0744, 013-60-8762"
string.gsub /\b(\d{3})\D?(\d{2})\D?(\d{4})\b/, '\1-\2-\3'
#=> "234-60-1422, 350-80-0744, 013-60-8762"
答案 1 :(得分:1)
s.gsub!(/\D/, '').insert(3, '-').insert(6, '-')