[英]reference matches in a string gsub regexp
Say I have a string like this 说我有这样的字符串
"some3random5string8"
I want to insert spaces after each integer so it looks like this 我想在每个整数后插入空格,所以它看起来像这样
"some3 random5 string8"
I specifically want to do this using gsub
but I can't figure out how to access the characters that match my regexp. 我特别想用gsub
做这个,但我无法弄清楚如何访问与我的正则表达式匹配的字符。
For example: 例如:
temp = "some3random5string8"
temp.gsub(/\d/, ' ') # instead of replacing with a ' ' I want to replace with
# matching number and space
I was hoping there was a way to reference the regexp match. 我希望有一种方法可以引用正则表达式匹配。 Something like $1
so I could do something like temp.gsub(/\\d/, "#{$1 }")
(note, this does not work) 像$1
这样的东西,所以我可以做一些像temp.gsub(/\\d/, "#{$1 }")
(注意,这不起作用)
Is this possible? 这可能吗?
From the gsub
docs: 来自gsub
文档:
If replacement is a String it will be substituted for the matched text. 如果replacement是String,它将替换匹配的文本。 It may contain back-references to the pattern's capture groups of the form \\d, where d is a group number, or \\k, where n is a group name. 它可能包含对格式\\ d形式的模式捕获组的反向引用,其中d是组号,或者\\ k,其中n是组名。 If it is a double-quoted string, both back-references must be preceded by an additional backslash. 如果它是双引号字符串,则两个反向引用都必须以额外的反斜杠开头。
This means the following 3 versions will work 这意味着以下3个版本将起作用
>> "some3random5string8".gsub(/(\d)/, '\1 ')
=> "some3 random5 string8 "
>> "some3random5string8".gsub(/(\d)/, "\\1 ")
=> "some3 random5 string8 "
>> "some3random5string8".gsub(/(?<digit>\d)/, '\k<digit> ')
=> "some3 random5 string8 "
Edit: also if you don't want to add an extra space at the end, use a negative lookahead for the end of line, eg: 编辑:如果您不想在末尾添加额外的空格,请在行尾使用负向前瞻,例如:
>> "some3random5string8".gsub(/(\d(?!$))/, '\1 ')
=> "some3 random5 string8"
A positive lookahead checking for a "word character" would also work of course: 检查“单词字符”的正向前瞻当然也会起作用:
>> "some3random5string8".gsub(/(\d(?=\w))/, '\1 ')
=> "some3 random5 string8"
Last but not least, the simplest version without a space at the end: 最后但并非最不重要的是,最简单的版本,最后没有空格:
>> "some3random5string8".gsub(/(\d)(\w)/, '\1 \2')
=> "some3 random5 string8"
gsub
采用了一个块,对于我来说,比无块的方式更容易记住。
"some3random5string8".gsub(/\d/){|digit| digit << " "}
Not sure about ruby syntax, but: 不确定ruby语法,但是:
temp.gsub(/(\d)/, '$1 ')
or 要么
temp.gsub(/(\d)/, '\1 ')
To be sure you insert space between number and a non number(ie letter or special char): 为了确保在数字和非数字(即字母或特殊字符)之间插入空格:
temp.gsub(/(\d)(\D)/, '$1 $2')
我对ruby不是很熟悉,但是我希望你可以捕获数字,然后像这样插入替换...
temp.gsub(/(\d)/, '$1 ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.