Ruby %r{} 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12384704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The Ruby %r{ } expression
提问by Alexandre
In a model there is a field
在模型中有一个字段
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:
对我来说看起来很奇怪。我知道这是一个正则表达式。但我想:
- 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{value}等于/value/? - 能够用普通的 Ruby 正则表达式运算符
/some regex/或~=. 是否可以?
回答by Eureka
%r{}is equivalent to the /.../notation, but allows you to have '/' in your regexp without having to escape them:
%r{}相当于/.../表示法,但允许您在正则表达式中使用 '/' 而不必转义它们:
%r{/home/user}
is equivalent to:
相当于:
/\/home\/user/
This is only a syntax commodity, for legibility.
为了易读性,这只是一种语法商品。
Edit:
编辑:
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)
Edit 2:
编辑2:
Note that the %r{}xvariant ignores whitespace, making complex regexps more readable. Example from GitHub's Ruby style guide:
请注意,该%r{}x变体忽略空格,使复杂的正则表达式更具可读性。来自GitHub 的 Ruby 风格指南的示例:
regexp = %r{
start # some text
\s # white space char
(group) # first group
(?:alt1|alt2) # some alternation
end
}x
回答by Samy Dindane
\.=> contains a dot(gif|jpg|jpeg|png)=> then, either one of these extensions$=> the end, nothing after iti=> case insensitive
\.=> 包含一个点(gif|jpg|jpeg|png)=> 然后,这些扩展中的任何一个$=> 结尾,后面没有任何内容i=> 不区分大小写
And it's the same as writing /\.(gif|jpg|jpeg|png)$/i.
这和写作一样/\.(gif|jpg|jpeg|png)$/i。
回答by xdazz
With %r, you could use any delimiters.
使用%r,您可以使用任何分隔符。
You could use %r{}or %r[]or %r!!etc.
你可以使用%r{}或%r[]或%r!!等。
The benefit of using other delimeters is that you don't need to escape the /used in normal regex literal.
使用其他分隔符的好处是您不需要转义/普通正则表达式中的used。
回答by Erez Rabih
this regexp matches all strings that ends with .gif, .jpg...
此正则表达式匹配所有以 .gif、.jpg 结尾的字符串...
you could replace it with
你可以用
/\.(gif|jpg|jpeg|png)$/i
回答by Hauleth
It mean that image_file_namemust end ($) with dot and one of gif, jpg, jpeg or png.
这意味着image_file_name必须$以点结尾 ( ) 和 gif、jpg、jpeg 或 png 之一。
Yes %r{}mean exactly the same as //but in %r{}you don't need to escape /.
Yes 的%r{}意思与//but in %r{}you don't need to escape完全相同/。

