문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top