Ruby gsub/regex 修饰符? [英] Ruby gsub / regex modifiers?

查看:48
本文介绍了Ruby gsub/regex 修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪里可以找到有关 gsub 修饰符的文档?\a \b \c \1 \2 \3 %a %b %c $1 $2 %3 等等?

Where can I find the documentation on the modifiers for gsub? \a \b \c \1 \2 \3 %a %b %c $1 $2 %3 etc.?

具体来说,我在看这段代码... something.gsub(/%u/, unit) %u 是什么?

Specifically, I'm looking at this code... something.gsub(/%u/, unit) what's the %u?

推荐答案

Zenspider 的 Quickref 包含一个部分解释 哪些转义序列可以在正则表达式中使用 和一个列出 由正则表达式匹配设置的>伪变量.在 gsub 的第二个参数中,您只需使用反斜杠而不是 $ 编写变量的名称,并在应用正则表达式后将其替换为该变量的值.如果使用双引号字符串,则需要使用两个反斜杠.

Zenspider's Quickref contains a section explaining which escape sequences can be used in regexen and one listing the pseudo variables that get set by a regexp match. In the second argument to gsub you simply write the name of the variable with a backslash instead of a $ and it will be replaced with the value of that variable after applying the regexp. If you use a double quoted string, you need to use two backslashes.

当使用 gsub 的块形式时,您可以直接使用变量.如果您返回一个包含例如的字符串\1 来自块,不会被 $1 替换.只有在使用双参数形式时才会发生这种情况.

When using the block-form of gsub you can simply use the variables directly. If you return a string containing e.g. \1 from the block, that will not be replaced with $1. That only happens when using the two-argument form.

这篇关于Ruby gsub/regex 修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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