簡體   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