从 werkzeug/Flask 路由规则中捕获类型 and/or 参数化路径的规则

Rule for capturing types and/or parameterized paths from werkzeug/Flask routing rules

我有一套Flask路由

/<string:name>/<path:id>/
/<name>/<path:id>/ 
/<string:name>/<id>/

我想使用正则表达式提取 nameid

/{name}/{id}/
/{name}/{id}/ 
/{name}/{id}/

对于所有这些(一个正则表达式来统治它们),适用于具有 type:path 的路径,如 /<string:name>/ 以及没有类型的路径,如 /<name>/

但我正在尝试:

(<(.*?\:)?(.*?)>)

只能匹配

/{name}/{id}/
/{id}/  # <--- Why this is not matching /{name}/{id}/
/{name}/{id}/

有 REGEX 专家帮忙吗?

在线正则表达式https://regex101.com/r/iL3jK2/3
问题https://github.com/rochacbruno/flasgger/issues/10

我建议使用

(<([^<>]*:)?([^<>]*)>)

regex demo is here。不确定你是否真的需要外部 (...)(仅当你将它与 re.findall 一起使用时,但你可以删除它们并使用 re.finditer 并使用 match.group(0) 访问所有匹配项)。

解释:

  • <([^<>]*:)? - 可选的第 2 组匹配
    • < - 文字 <
    • [^<>]* - <>
    • 以外的零个或多个字符
    • : - 文字 :
  • ([^<>]*) - 第 3 组匹配 <>
  • 以外的零个或多个字符
  • >收盘>

您的模式相当贪婪,因为 .*? 匹配尽可能多的字符以到达第一个 :。因此,它直接进入 id,忽略 name。当使用取反字符class[^<>]时,肯定不会通过>去匹配里面的name第一对 <...>.