The regular expression matches the url in the url

I need a regex that 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 three types, but it matches /foobar too, which I don't want. What should I add to the regex so that it doesn't match /foobar ?

+4
source share
5 answers

Try the following:

 ^http://example\.com/foo(?:/.*)?$ 
+4
source

In your regex, the last /? means optional / at the end. Thus, /foobar also mapped. Try the following:

 http:\/\/example\.com\/foo($|\/.*) 
+1
source

Try something like this:

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

In the form of a regular expression:

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

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


Some explanations:

  • (foo|bar) matches foo or bar
  • (?:) group with ?: will not be recorded at the beginning
  • \/ will match / at the end
  • \/(\w+) matches the character / with a word that is repeated one or more times
  • |) will not match the bottom at the end of the line.
0
source

I would use a negative lookahead ( ?! ) For this:

 $urls = array( 'http://example.com/foo', 'http://example.com/foo/', 'http://example.com/foo/bar', 'http://example.com/foobar' ); foreach ($urls as $url) { if (preg_match('#^http://example\.com/foo(?!bar)#', $url)) { echo $url, " matches.\n"; } else { echo $url, " does NOT match.\n"; } } // Output: // http://example.com/foo matches. // http://example.com/foo/ matches. // http://example.com/foo/bar matches. // http://example.com/foobar does NOT match. 
0
source

Javascript regex

https: ?? // (example.com) // [^ /] * / (bar)

Test here: (More ..)

http://tools.netshiftmedia.com/regexlibrary/

0
source

Source: https://habr.com/ru/post/1392690/


All Articles