使用RegExp格式化字符串以设置定界符 [英] Formatting string with RegExp to set delimiter

查看:50
本文介绍了使用RegExp格式化字符串以设置定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按以下格式设置字符串

I'm trying to format a string as follows

确保所有数字均使用破折号作为分隔符。
例如:480.01.4430和480014430都是480-01-4430。

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


推荐答案

很奇怪,您没有得到例外:必须将 gsub 的第二个参数设置为字符串(或可以转换为字符串的东西),而不是正则表达式。

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.

这是一个工作示例:

ssn = '123456789'
ssn.gsub(/(\d{3})(\d{2})(\d{3})/, '\1-\2-\3')
# => "123-45-6789"

原始字符串中包含三组数字。我们将每个组括在括号中。每对括号都会创建一个 match组。在替换字符串中,我们使用 \1 包括第一个匹配组, \2 包括第二个匹配组匹配组,然后 \3 包括第三个匹配组,并在它们之间加上破折号。

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.

这篇关于使用RegExp格式化字符串以设置定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆