Pergunta

I'm having problems writing an all encompassing regular expression for the following.

I have a url in the format

www.someurl.com/dir1/dir2/dir3/page?bunchofrandomvariables

I also have a slightly modified version of this URL going

www.someurl.com/dir1/newdirectory/dir2/dir3/page?bunchofrandomvariables

Where newdirectory can be alphanumeric and can include dashes.

I want a regular expresssion that can match on the original URL (with no "newdirectory") AND any "newdirectory" that comes to pass.

My first attempt was something akin to

^www.someurl.com/dir1/[a-zA-Z]+/dir2/dir3/page?.*

Unfortunately, that breaks the 1st example, since the [a-zA-Z]+ captures "dir2". Is there anyway to write this with lookaheads to capture both examples in one line?

Foi útil?

Solução

I just modified your regex:

  • Escaped the slaches (maybe it's not required depending of the language you're using)
  • made the /newdirectory part optional using ?

    ^www.someurl.com\/dir1(\/[a-zA-Z]+)?\/dir2\/dir3\/page?.*
    

Working DEMO

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top