Regular Expression to match both relative and absolute URLs

后端 未结 6 1230
自闭症患者
自闭症患者 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 04:00

    Not easy and you maybe end up having "too much URI" catched, however what about:

    ((http://|https://)([^/])+)*(/([^\s])*(/))(((\w)*\.[\w]{3,10})|(\w+))?
    

    Basically you have a couple of groups there. On defining the protocol. One is looking for the directory and one is looking for a file at the end. But! this approach is very limited. If you need a real URI validation and! separation (port, username, password, filter out unwanted characters!) you will probably end up with a way more complex expression. Good luck!

    Update:

    You didn't asked for this, however for those guys coming from search engines wanting to learn more about regex I would like to plug this free program I used for this attempt "The Regex Coach" (Nope, not affiliated).

提交回复
热议问题