[英]How to combine Ruby regexp conditions
我需要检查一个字符串是否是有效的图像网址。 我想检查字符串的开头和字符串的结尾,如下所示:
到目前为止,我有:
(https?:)
我似乎无法指示字符串\\A
开头,组合模式,并测试字符串的结尾。
测试字符串:
"http://image.com/a.jpg"
"https://image.com/a.jpg"
"ssh://image.com/a.jpg"
"http://image.com/a.jpeg"
"https://image.com/a.png"
"ssh://image.com/a.jpeg"
请参阅http://rubular.com/r/PqERRim5RQ
使用Ruby 2.5
使用您自己的演示,您可以使用
^https?:\/\/.*(?:\.jpg|\.png|\.gif|\.jpeg)$
查看修改过的演示 。
^https?:\\/\\/.*\\.(?:jpe?g|png|gif)$
请参阅后者的演示 。
^
和$
),表示字符串的开始/结束。
另外,请记住,如果你想要,你需要逃避点( \\.
) .
。
^ - is meant for the start of a string (or a line in multiline mode, but in Ruby strings are always in multiline mode) $ - is meant for the end of a string / line \\A - is the very start of a string (irrespective of multilines) \\z - is the very end of a string (irrespective of multilines)
你可以用
reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}
重点是:
^
和$
并在实际代码中使用\\A
和\\z
。 \\A
和\\z
锚点 /
,则使用%r{pat}
语法,它更清晰。 在线Ruby测试 :
urls = ['http://image.com/a.jpg',
'https://image.com/a.jpg',
'ssh://image.com/a.jpg',
'http://image.com/a.jpeg',
'https://image.com/a.png',
'ssh://image.com/a.jpeg']
reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}
urls.each { |url|
puts "#{url}: #{(reg =~ url) == 0}"
}
输出:
http://image.com/a.jpg: true
https://image.com/a.jpg: true
ssh://image.com/a.jpg: false
http://image.com/a.jpeg: true
https://image.com/a.png: true
ssh://image.com/a.jpeg: false
这里的答案非常好,但是如果你想避免使用复杂的正则表达式并更清楚地向读者传达你的意图,你可以让URI
和File
为你做繁重的工作。
(而且由于你使用的是2.5,我们使用#match?
代替其他正则表达式匹配方法。)
def valid_url?(url)
# Let URI parse the URL.
uri = URI.parse(url)
# Is the scheme http or https, and does the extension match expected formats?
uri.scheme.match?(/https?/i) && File.extname(uri.path).match?(/(png|jpe?g|gif)/i)
rescue URI::InvalidURIError
# If it's an invalid URL, URI will throw this error.
# We'll return `false`, because a URL that can't be parsed by URI isn't valid.
false
end
urls.map { |url| [url, valid_url?(url)] }
#=> Results in:
'http://image.com/a.jpg', true
'https://image.com/a.jpg', true
'ssh://image.com/a.jpg', false
'http://image.com/a.jpeg', true
'https://image.com/a.png', true
'ssh://image.com/a.jpeg', false
'https://image.com/a.tif', false
'http://t.co.uk/proposal.docx', false
'not a url', false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.