duandingyou3331 2019-07-26 17:30
浏览 36
已采纳

重复的任意捕获组

Given a string, eg.:

static_string.name__john.id__6.foo__bar.final_string

but with an arbitrary number of label__value. components, how can I repeat the capture groups, split them into label & value, and also capture the terminating final_string ?

For the above I'd want [name, john, id, 6, foo, bar, final_string]

Is something like this possible when I don't know the number of label__value. components in advance?

This is for golang / RE2 if that matters.

Update: I don't have the luxury of doing this in a few lines of code, and would need to do this in a single regex. The regex is defined in a config file to an application I don't control, so a code based loop with conditionals etc is unfortunately not possible.

  • 写回答

1条回答 默认 最新

  • douwei1128 2019-07-26 19:21
    关注

    This totally depends on what the thing you are putting this into expects.

    This is answer focused on getting you the capture groups in a basic way attempting to avoid any issues with the "thing" you are putting the regex into and RE2.

    Note: You might find that the final_string doesn't get the capture group index you expect with this method, but again depends on what you are putting the regex into.

    A regular expression that would match "one" and "no" key/value pairs the following is:

    ^[^.]+(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+))$
    
    • static_string.final_string
    • static_string.name__john.final_string

    To support one more key/value pair we repeat part of the regular expression: Part repeated:

    (?:\.([^.]+?)__([^.]+))?
    

    So to support 2 key value pairs the regular expression is:

    ^[^.]+(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+))$
    

    This now supports the following additional example:

    • static_string.name__john.foo__bar.final_string

    So if I expand that out to support 12 key value pairs the regular expression is:

    ^[^.]+(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+?)__([^.]+))?(?:\.([^.]+))$
    

    This supports the following additional examples:

    • static_string.name__john.id__6.foo__bar.final_string
    • static_string.name2_1b__john.id__6.foo__bar.final_string
    • static_string.name__john.id__6.foo__bar.name__john.id__6.foo__bar.name__john.id__6.foo__bar.name__john.id__6.foo__bar.final_string
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题