Regular Expression to match relative URLs

2019-04-02 09:26发布

问题:

Looking for a regular expression that match the following relative URLs:

All urls starts with /abc/ but we don't know where it ends and it doesn't have any file extension at the end.

/abc/xyz

/abc/part1/part2

/abc/red/blue/white/green/black

and so on.

Any help?

回答1:

Try this regular expression:

/abc/(?:[A-Za-z0-9-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})*(?:/(?:[A-Za-z0-9-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})*)*

This is derived from the ABNF of a generic URI.



回答2:

/^\/abc\//

However my guess is you are missing something in the question....



回答3:

The answer I write here is for PHP; at the moment I am writing it, you didn't report for which programming language you are interested to have an answer.

  • If you want a regular expression to check if the path starts with /abc/

    preg_match('|^/abc/.*$|i', $path);

  • If you want a regular expression that returns the part after /abc/

    preg_match('|^/abc/(.*)$|i', $path, $matches);

In both the cases, regular expressions can be avoided; you can use string functions.