admin管理员组文章数量:1400583
I know there are other questions with the same title but I couldn't find an answer within them.
I have a string that could be /action
or /action{key:value}
I'm trying to get action
, key
and value
in variables.
I've tried several regexps that are variations of this one:
/^\/(.*?)(\{(.*)\:(.*)\})?/
/^\/(.*?)\{(.*)\:(.*)\}/
matches /action{key:value}
but not /action
/^\/(.*)(\{(.*)\:(.*)\})?/
(declaring the capture group as optional) matches /action
but not /action{key:value}
(it captures everything)
So if I declare the first group as lazy :
/^\/(.*?)(\{(.*)\:(.*)\})?/
it doesn't match anything anymore.
I know I'm close to the solution but I'm sure misunderstanding something basic :)
I know there are other questions with the same title but I couldn't find an answer within them.
I have a string that could be /action
or /action{key:value}
I'm trying to get action
, key
and value
in variables.
I've tried several regexps that are variations of this one:
/^\/(.*?)(\{(.*)\:(.*)\})?/
/^\/(.*?)\{(.*)\:(.*)\}/
matches /action{key:value}
but not /action
/^\/(.*)(\{(.*)\:(.*)\})?/
(declaring the capture group as optional) matches /action
but not /action{key:value}
(it captures everything)
So if I declare the first group as lazy :
/^\/(.*?)(\{(.*)\:(.*)\})?/
it doesn't match anything anymore.
I know I'm close to the solution but I'm sure misunderstanding something basic :)
Share Improve this question asked Jan 28, 2019 at 10:05 MrVoodooMrVoodoo 1,0831 gold badge17 silver badges25 bronze badges 1-
@SebastianProske Well, second example captures everything in the first capture group. Meaning
/action{key:value}
is captured as a whole and not in separate groups. – MrVoodoo Commented Jan 28, 2019 at 10:11
1 Answer
Reset to default 6Put the whole {...}
part in an optional non-capturing group, while keeping the first group lazy:
^\/(.*?)(?:{(.*)\:(.*)})?$
^^^ ^
https://regex101./r/S4DAy3/1
Or use a negative character set, excluding {
s:
^\/([^{]+)(?:{(.*)\:(.*)})?$
本文标签: javascriptRegex with optional capture groupsStack Overflow
版权声明:本文标题:javascript - Regex with optional capture groups - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744223422a2595975.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论