I could use some help writing a regular expression. In my Django application, users can hit the following URL:
http://www.example.com/A1/B2/C3
I’d like to create a regular expression that allows accepts any of the following as a valid URL:
http://www.example.com/A1 http://www.example.com/A1/B2 http://www.example.com/A1/B2/C3
I’m guessing I need to use the ‘OR’ conditional, but I’m having trouble getting my regex to validate. Any thoughts?
UPDATE: Here is the regex so far. Note that I have not included the ‘http://www.example.com‘ portion — Django handles that for me. I’m just concerned with validating 1,2, or 3 subdirectories.
^(\w{1,20})|((\w{1,20})/(\w{1,20}))|((\w{1,20})/(\w{1,20})/(\w{1,20}))$
Skip the
|, use the?and()http://www\.example\.com/A1(/B2(/C3)?)?And if you replace the A1-C3 with a pattern:
http://www\.example\.com/[^/]*(/[^/]*(/[^/]*)?)?Explanation:
http://www.example.com/A1/B2and even an additional/C3, but/C3is only matched, when there is a/B2[^/]*(as many non slashes as possible)http://www\.example\.com/([^/]*)(/([^/]*)(/([^/]*))?)?Will give (
groupnumber: content):You can check it out online here or get this tool (yes it’s free, and it’s even written in Lisp…).