[英]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.