javascript - Regex with optional capture groups - Stack Overflow

I know there are other questions with the same title but I couldn't find an answer within them.I h

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
Add a ment  | 

1 Answer 1

Reset to default 6

Put 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

相关推荐

  • javascript - Regex with optional capture groups - Stack Overflow

    I know there are other questions with the same title but I couldn't find an answer within them.I h

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信