Regular Expression to match both relative and absolute URLs

后端 未结 6 1227
自闭症患者
自闭症患者 2021-02-09 03:12

Anyone want to try their hand at coming up with a regex that matches both:

  • /foo/bar/baz.gif
  • /foo/bar/
  • http://www.foo.com/foo/bar

I

6条回答
  •  执念已碎
    2021-02-09 03:49

    I used naming capture groups. We get better matches when the scheme is present. Like www.foo.com/bar would only match /bar.

    (?:
      (?:(?https?|file)://)
      (?[^/]+)
      (?/(?:[^\s])+)?
    )
    |
    (?/(?:[^\s])+)
    

    This is what you could do for javascript

    var result = text.match(/(?:(?:(https?|file):\/\/)([^\/]+)(\/(?:[^\s])+)?)|(\/(?:[^\s])+)/g);
    

    Test data

    sadfasdf /foo/bar/ba090z.gif asdfasdf /foo/bar/ sadfasdf asdflkj; http://www.foo.com/foo/bar some stuff http://user:pw@www.foo.com:80/r?stuff%20stuff
    
    user:pw@www.foo.com:80/r?stuff%20stuff
    

提交回复
热议问题