Match all occurrences of glued URLs

Viewed 46

Given a string like:

https://www.test.com/http://www.test2.com COOL http://www.test3.com/http://www.test4.com

How can I write a regex string that will output this into an array of 4?

Output: ['https://www.test.com/, 'http://www.test2.com COOL', 'https://www.test3.com/', 'https://www.test4.com']

The issue I am having is knowing how to tell the regex to end at the next occurrence of either https or http since in the string example, there may or may not be a space between each URL or an ending /

My regex so far: (https:\/\/www.|http:\/\/www.)

2 Answers

To match all URLs that can be potentially glued to one another, you can use

https?:\/\/.*?(?=\s*https?:\/\/|$)

See the regex demo.

Details:

  • https?:\/\/ - http:// or https://
  • .*? - any zero or more chars other than line break chars, as few as possible
  • (?=\s*https?:\/\/|$) - a positive lookahead that matches a location that is immediately followed with either
    • \s*https?:\/\/ - zero or more whitespaces, https:// or http://
    • | - or
    • $ - end of string.

If using Javascript or any language that supports regex splits then try this:

/ *(?=https?:\/\/)/

console.log(`https://www.test.com/http://www.test2.com COOL http://www.test3.com/http://www.test4.com`.split(/ *(?=https?:\/\/)/));

Related