繁体   English   中英

如何结合Ruby regexp条件

[英]How to combine Ruby regexp conditions

我需要检查一个字符串是否是有效的图像网址。 我想检查字符串的开头和字符串的结尾,如下所示:

  • 必须以http(s)开头:
  • 必须以.jpg | .png | .gif | .jpeg结尾

到目前为止,我有:

(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}

重点是:

  1. 当在网上正则表达式测试仪测试 ,你正在测试一个多行字符串,但在现实生活中,你会验证线作为单独的字符串。 因此,在这些测试人员中,使用^$并在实际代码中使用\\A\\z
  2. 要匹配字符串而不是行,您需要\\A\\z锚点
  3. 如果您的模式中有许多/ ,则使用%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

这里的答案非常好,但是如果你想避免使用复杂的正则表达式并更清楚地向读者传达你的意图,你可以让URIFile为你做繁重的工作。

(而且由于你使用的是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM