I need to check if a string is valid image url. I want to check beginning of string and end of string as follows:
So far I have:
(https?:)
I can't seem to indicate beginning of string \A
, combine patterns, and test end of string.
Test strings:
"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"
Please see http://rubular.com/r/PqERRim5RQ
Using Ruby 2.5
Using your very own demo, you could use
^https?:\/\/.*(?:\.jpg|\.png|\.gif|\.jpeg)$
See the modified demo.
^https?:\/\/.*\.(?:jpe?g|png|gif)$
See a demo for the latter as well.
^
and $
) on both sides, indicating the start/end of the string. Additionally, please remember that you need to escape the dot (\.
) if you want to have .
.
^ - 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)
You may use
reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}
The point is:
^
and $
and in real code, use \A
and \z
.\A
and \z
anchors%r{pat}
syntax if you have many /
in your pattern, it is cleaner.Online Ruby test:
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}"
}
Output:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With