Ruby正则表达式-gsub是否存储匹配的内容? [英] Ruby regex- does gsub store what it matches?

查看:69
本文介绍了Ruby正则表达式-gsub是否存储匹配的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用

.gsub(/matchthisregex/,"replace_with_this")

gsub是否将与正则表达式匹配的内容存储在某个地方?我想在替换字符串中使用匹配的内容.例如类似

does gsub store what it matches with the regex somewhere? I'd like to use what it matches in my replacement string. For example something like

"replace_with_" + matchedregexstring + "this"

在我上面的示例中,matchedregexstring是gsub存储的匹配项吗?抱歉,这令人困惑,我不知道该怎么说.

in my above example where the matchedregexstring would be the stored match from gsub? Sorry if that was confusing, I don't know how else to word that.

推荐答案

来自

如果替换String,它将替换匹配的文本.它可能包含对格式为\d的模式捕获组的反向引用,其中 d 是组号,或者\k<n>,其中 n 是组名.如果它是双引号引起来的字符串,则两个反向引用都必须在前面加上一个额外的反斜杠.但是,在替换中,特殊匹配变量(例如&$)将不引用当前匹配项.
[...]
在块形式中,当前匹配字符串作为参数传递,并且将适当设置诸如$1$2,$`,$&$'之类的变量.该块返回的值将替换为每次调用时的匹配项.

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k<n>, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.
[...]
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

如果您不关心捕获组(即正则表达式中的(expr)之类的东西),则可以使用块形式和$&:

If you don't care about capture groups (i.e. things like (expr) in the regex) then you can use the block form and $&:

>> 'where is pancakes house?'.gsub(/is/) { "-#{$&}-" }
=> "where -is- pancakes house?"

如果您有捕获组,则可以在替换字符串中使用\n:

If you do have capture groups then you can use \n in the replacement string:

>> 'where is pancakes house?'.gsub(/(is)/, '-\1-')
=> "where -is- pancakes house?"

块中的

$n:

>> 'where is pancakes house?'.gsub(/(is)/) { "-#{$1}-" }
=> "where -is- pancakes house?"

这篇关于Ruby正则表达式-gsub是否存储匹配的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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