ruby-on-rails - Ruby Rails %r 和 %w

标签 ruby-on-rails ruby regex

我认为有两个问题是相关的,并且我认为与正则表达式相关,但在一些毫无结果的谷歌搜索后让我陷入困境。

validates :image_url, format: { with: %r{\.(gif|jpg)\Z}i }

我的猜测:类似于 ruby​​/regex i = 忽略大小写,单管道表示“或”。猜测\Z 表示字符串结束。括号只是容器,与 ruby​​/regex 不同,它们表示的东西截然不同。

但是 %r 是做什么的?我还没有在 ruby​​/regex 中遇到过这个。

ok_urls = %w{ fred.gif fred.jpg FRED.Jpg}

%r 和 %w 似乎在做同样的事情,所以我很困惑为什么有两个单独的命令来做同样的事情。抱歉,如果这不是很清楚。

最佳答案

一个Regexp包含一个正则表达式,用于将模式与字符串进行匹配。 正则表达式是使用 /.../%r{...} 文字以及 Regexp::创建的新的构造函数。

%r and %w seem to be doing the same thing so I'm confused..

%w{ fred.gif fred.jpg FRED.Jpg}
# => ["fred.gif", "fred.jpg", "FRED.Jpg"]
%r{ a b }
# => / a b /

没有。正如您在上面看到的,它们并不相同。

One thing I noticed%r{},因为您不需要转义斜杠

# /../ literals:
url.match /http:\/\/example\.com\//
# => #<MatchData "http://example.com/">

# %r{} literals:
url.match %r{http://example\.com/}
# => #<MatchData "http://example.com/">

Use %r仅适用于匹配多个“/”字符的正则表达式。

# bad
%r(\s+)

# still bad
%r(^/(.*)$)
# should be /^\/(.*)$/

# good
%r(^/blog/2011/(.*)$)

关于ruby-on-rails - Ruby Rails %r 和 %w,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623684/

相关文章:

ruby-on-rails - Rails : Why is with_exclusive_scope protected? 关于如何使用它有什么好的实践吗?

ruby-on-rails - Rails Active_Admin VS。我自己的后端

ruby - 如何重用 Vagrantfile 中引用行中的变量?

ruby-on-rails - 避免本地化文件重复

ruby-on-rails - IE 8 中的 Rails 4 Bootstrap 3 header 问题

MySQL Regex - 如何查找特定的连续单词集

ruby-on-rails - Rails 确定关联是 has_one 还是 has_many

sql - Postgres 查询 ILIKE 和 "%#{}%"

html - 如何检查字符串是否包含html标签最通用的方法

javascript - 正则表达式仅删除第一个实例