How to combine Ruby regexp conditions

ruby string match regex
ruby regex examples
ruby gsub regex
ruby match
ruby regex flags
ruby match exact string
ruby
ruby regex start of string

I need to check if a string is valid image url. I want to check beginning of string and end of string as follows:

  • Must start with http(s):
  • Must end by .jpg|.png|.gif|.jpeg

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

You may use

reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}

The point is:

  1. When testing at online regex testers, you are testing a single multiline string, but in real life, you will validate lines as separate strings. So, in those testers, use ^ and $ and in real code, use \A and \z.
  2. To match a string rather than a line you need \A and \z anchors
  3. Use %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

Using conditionals inside Ruby regular expressions, Of the many new features that Ruby 2.0 shipped back in 2013, the So let's combine the regular expressions above, and surround each section with parentheses. Two of the most common options for your condition, A are:. Combine Regexp? Ask Question To make single regex if user enter multiple conditions, I combine them with " decimals and alphanumeric data in Ruby. 1.

Using your very own demo, you could use

^https?:\/\/.*(?:\.jpg|\.png|\.gif|\.jpeg)$

See the modified demo.


One could even simplify it to:

^https?:\/\/.*\.(?:jpe?g|png|gif)$

See a demo for the latter as well.


This basically uses anchors (^ 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 ..
There's quite some ambiguity going on in the comments section, so let me clarify this:

^  - 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) 

Ruby Regular Expressions (Complete Tutorial), We can combine everything we learned so far to create more complex regular expressions. Example: Does this look like an IP address? Using conditionals inside Ruby regular expressions. In this post, we'll dive into regex conditionals and discuss how to work around the limitations in Ruby's implementation of them

The answers here are quite good, but if you wanted to avoid using a complicated regex and communicate your intent more clearly to a reader, you could let URI and File do the heavy lifting for you.

(And since you're using 2.5, let's use #match? instead of other regex-matching methods.)

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

Class: Regexp (Ruby 2.5.1), A Regexp holds a regular expression, used to match a pattern against strings. The vertical bar metacharacter ( | ) combines two expressions into a single one  With Regexp, regular expressions, we use a text language to better handle this data. Ruby provides an operator, "~=" to make regular expressions easier to use.

Ruby Regexp Class, Otherwise, the substitutions will be performed every time the literal generates a Regexp object. You can combine multiple modifiers by stringing them together as​  Left to right ordering is used as a tie-breaker if multiple alternations match starting from same location. You also learnt couple of Regexp methods that help to programmatically construct a regexp literal. Escaping metacharacters. You have seen a few metacharacters and escape sequences that help to compose a regexp literal.

Regex Tutorial - If-Then-Else Conditionals, In Perl's regex flavor, and compatible flavors, you can use a special construct to parentheses, like in (?(?=condition)(then1|then2|then3)|(else1|else2|else3)). Boost and Ruby treat a conditional that references a non-existent capturing  Regexp, captures. This example combines many constructs in Ruby. We use an iterator (each) over a string array. We then use a case-statement with regular expressions. Tip: After a Regexp matches a value in a case, its groups are stored in a special variable $1. We get the captured value there.

Regular expressions in Ruby, In this part of the Ruby tutorial, we cover regular expressions. We can combine characters into character classes with the square brackets. A character class matches The 'car' strings meets these conditions. p "23af 433a  Ruby - Regular Expressions - A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a patt

Comments
  • So people down in the answers section are having an argument about whether your "test strings" are (1) many strings, one per line, with no whitespace or (2) a single string where a regex has to match each individual line. Can you edit the question to clarify that?
  • Thanks for the explanations. Much appreciated
  • This obviously matches "foo\nhttp.....jpg\nbar" which neither starts with "http" nor ends with "jpg". Always use \A and \z anchors instead of ^ and $ unless you perfectly understand the circumstances.
  • I think you don't need second grouping: ^https?:\/\/.*\.(?:jpe?g|png|gif)$
  • @revo I am good at reading first sentences of the OP. It states: "I need to check if a string is valid image url."
  • @mudasobwa And I hope you are good at reading OP's provided demo in which there are URLs each in a single line?
  • @revo: Thanks, that's exactly the point of using ^ and $ over \A and \Z.