Skip to content

Instantly share code, notes, and snippets.

@veganstraightedge
Last active February 12, 2017 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veganstraightedge/0a20d0c17c7b6c56c69172cf0051d2f2 to your computer and use it in GitHub Desktop.
Save veganstraightedge/0a20d0c17c7b6c56c69172cf0051d2f2 to your computer and use it in GitHub Desktop.
I need help writing this regex. Maybe it's obvious to someone else, but I keep failing one while matching the other or vice versa.

I need help writing this regex. Maybe it's obvious to someone else, but I keep failing one while matching the other or vice versa.

In Ruby.

Here are the the three test cases that I need to meet.

[[https://example.com/photo.png]]
[[https://example.com/video.mp4 With a text caption that's always separated from the URL by at least one space.]]
[[https://example.com/photo.png]] [[https://example.com/photo.png]]
  1. Should match the URL.
  2. Should match the URL and caption.
  3. Should match the URL two separate times.

If you come up with something, send it my way. Thanks! Sb

@bemurphy
Copy link

bemurphy commented Feb 12, 2017

Not pretty, but this works:

s1 = "[[https://example.com/photo.png]]"
s2 = "[[https://example.com/video.mp4 With a text caption that's always separated from the URL by at least one space.]]"
s3 = "[[https://example.com/photo2.png]] [[https://example.com/photo3.png]]"

def match(s)
  s.scan(/\[\[(http[^\]\s]+(?:\s.+)?)\]\]/).flatten
  # if you only want to capture the url:
  # s.scan(/\[\[([^\]\s]+)(?:\s.+)?\]\]/).flatten
end

p match(s1)
p match(s2)
p match(s3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment