[英]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. 在为我的站点编写API服务时,我意识到
String.split()
不会做得更长久,因此决定尝试使用正则表达式来碰碰运气。 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: 该URL表示一个函数调用:
/api/SECTION/FUNCTION/[PARAMS]
This last part, including the slash, is optional. 最后一部分(包括斜杠)是可选的。 Some functions display a JSON reply without having to receive any arguments.
一些函数无需接收任何参数即可显示JSON回复。 Example:
/api/sounds/getAllSoundpacks
prints a list of available sound packs. 示例:
/api/sounds/getAllSoundpacks
打印可用声音包的列表。 Though, /api/sounds/getPack/8Bit
prints the detailed information. 不过,
/api/sounds/getPack/8Bit
打印详细信息。
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/: 这将捕获URL中FUNCTION /之后的所有内容,而与FUNCTION /之后的其他内容无关:
FUNCTION\/(.+)$
The RegExp will not match if there is no part after FUNCTION. 如果在FUNCTION之后没有任何部分,则RegExp将不匹配。
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. 您的模式
/(.*)/(.*)/?(.*)
几乎是正确的,它有点太短-允许2或3个斜杠,但是您想接受3或4个斜杠的任何东西。 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 "///".)
(由于启用了多行模式,该模式看起来有所不同,但仍然可以使用。它也有点“更好”,因为它不匹配“ ///”之类的垃圾。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.