简体   繁体   中英

Capturing optional part of URL with RegExp

While writing an API service for my site, I realized that String.split() won't do it much longer, and decided to try my luck with regular expressions. I have almost done it but I can't find the last bit. Here is what I want to do:

The URL represents a function call:

/api/SECTION/FUNCTION/[PARAMS]

This last part, including the slash, is optional. Some functions display a JSON reply without having to receive any arguments. Example: /api/sounds/getAllSoundpacks prints a list of available sound packs. Though, /api/sounds/getPack/8Bit prints the detailed information.

Here is the expression I have tried:

req.url.match(/\/(.*)\/(.*)\/?(.*)/);

What am I missing to make the last part optional - or capture it in whole?

This will capture everything after FUNCTION/ in your URL, independent of the appearance of any further / after FUNCTION/:

FUNCTION\/(.+)$

The RegExp will not match if there is no part after FUNCTION.

This regex should work by making last slash and part after optional:

/^\/[^/]*\/[^/]*(?:\/.*)?$/

This matches all of these strings:

/api/SECTION/FUNCTION/abc
/api/SECTION
/api/SECTION/
/api/SECTION/FUNCTION

Your pattern /(.*)/(.*)/?(.*) was almost correct, it's just a bit too short - it allows 2 or 3 slashes, but you want to accept anything with 3 or 4 slashes. And if you want to capture the last (optional) slash AND any text behind it as a whole, you simply need to create a group around that section and make it optional:

/.*/.*/.*(?:/.+)?

should do the trick.

Demo. (The pattern looks different because multiline mode is enabled, but it still works. It's also a little "better" because it won't match garbage like "///".)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM