问题
I'm trying to format a string as follows
Ensure all of numbers use dashes for delimiters. Example: 480.01.4430 and 480014430 would both be 480-01-4430.
this is what I have come up with so far, but I can't understand why it doesn't work
def format_ssns(string)
ssn = string[/\d{9}/]
ssn.gsub(/\d{9}/, /\d{3}-\d{2}-\d{4}/)
end
回答1:
It's strange that you're not getting an exception: The second argument to gsub is required to be a String (or something that can be converted to a String), not a regexp.
Here's a working example:
ssn = '123456789'
ssn.gsub(/(\d{3})(\d{2})(\d{3})/, '\1-\2-\3')
# => "123-45-6789"
There are three groups of digits in the original string. We enclose each group in parentheses. Each pair of parentheses creates a match group. In the replacement string, we use \1
to include the first match group, \2
to include the second match group, and \3
to include the third match group, with dashes between them.
回答2:
If you don't care about anything in the string, than is not a digit, you can strip everything else and format as you want:
string.gsub(/\D/, '').gsub(/(\d{3})(\d{2})(\d{4})/, "\\1-\\2-\\3")
来源:https://stackoverflow.com/questions/15424323/formatting-string-with-regexp-to-set-delimiter