Ruby %r{} 表达式 [英] The Ruby %r{ } expression
本文介绍了Ruby %r{} 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
模型中有一个字段
validates :image_file_name, :format => { :with => %r{\.(gif|jpg|jpeg|png)$}i
对我来说看起来很奇怪.我知道这是一个正则表达式.但我想:
It looks pretty odd for me. I am aware that this is a regular expression. But I would like:
- 了解它的确切含义.
%r{value}
是否等于/value/
? - 能够用普通的 Ruby 正则表达式运算符
/some regex/
或~=
替换它.可能吗?
- to know what exactly it means. Is
%r{value}
equal to/value/
? - be able to replace it with normal Ruby regex operator
/some regex/
or~=
. Is it possible?
推荐答案
%r{}
等同于 /.../
符号,但允许您在您的正则表达式中有/"而不必转义它们:
%r{}
is equivalent to the /.../
notation, but allows you to have '/' in your regexp without having to escape them:
%r{/home/user}
相当于:
/\/home\/user/
为了易读性,这只是一种语法商品.
This is only a syntax commodity, for legibility.
请注意,您几乎可以使用任何非字母字符对来代替{}".这些变体也同样有效:
Note that you can use almost any non-alphabetic character pair instead of '{}'. These variants work just as well:
%r!/home/user!
%r'/home/user'
%r(/home/user)
编辑 2:
请注意,%r{}x
变体忽略空格,使复杂的正则表达式更具可读性.GitHub 的 Ruby 风格指南中的示例:>
Note that the %r{}x
variant ignores whitespace, making complex regexps more readable. Example from GitHub's Ruby style guide:
regexp = %r{
start # some text
\s # white space char
(group) # first group
(?:alt1|alt2) # some alternation
end
}x
这篇关于Ruby %r{} 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文