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:
^\/([^{]+)(?:{(.*)\:(.*)})?$
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744223423a4563891.html
评论列表(0条)