Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match word in a URL

Tags:

regex

I need a regular expression which matches:

http://example.com/foo
http://example.com/foo/
http://example.com/foo/bar

but not:

http://example.com/foobar

Using http://example.com/foo/? matches the three types, but it matches /foobar too that I don't want. What should I add to the regex to not match /foobar?

like image 630
Gergo Erdosi Avatar asked Jan 24 '12 13:01

Gergo Erdosi


2 Answers

Try this one:

^http://example\.com/foo(?:/.*)?$
like image 161
Toto Avatar answered Sep 20 '22 14:09

Toto


Try something like this:

http://example.com/foo(?:\/|/(\w+)|)

In regex form:

/http:\/\/example.com\/foo(?:\/|\/(\w+)|)/

This will match example.com/foo or example.com/foo/bar or example.com/foo/


Some explaination:

  • (foo|bar) matches foo or bar
  • (?:) a group with the ?: in the begin will not been captured
  • \/ will match a / at the end
  • \/(\w+) match a / with a word character who is repeated one or more times
  • |) will match nothing at the end of the string.
like image 40
Wouter J Avatar answered Sep 19 '22 14:09

Wouter J