Formatting string with RegExp to set delimiter

蹲街弑〆低调 提交于 2019-12-13 14:37:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!