Regular Expression to match both relative and absolute URLs

后端 未结 6 1247
自闭症患者
自闭症患者 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:59

    That's a tricky one because there are so many valid characters in URL's (before they get url encoded).

    Here's my shot:

    (http:/|https:/)?(/[^\s"'<>]+)+/?
    

    Also similar to Alex's. The only problem I found with Alex's is that it wouldn't match things like pound signs, dashes, stuff like that. Whereas mine will match all of that.

    EDIT -- In fact the only thing that keeps it from being too greedy is the instruction to NOT match whitespace, quotes, apostrophes, or chevrons.

提交回复
热议问题