.net regex 可选命名组

.net regex optional named groups

我想像这样解析输入字符串: client/02004C4F4F50/box/registration client/02004C4F4F50/box/data/flow

使用 .NET 正则表达式库。 clientbox 始终相同,但其余部分可能不同。 我想到的是这个正则表达式:

^client/(?<id>.+?)/box/(?<type>.+)(/(?<value>.+)?)

我想要的是 registrationdata 匹配到 type 组,而 flow 进入可选组 value。 它应该是这样的:

Groupname | Input 1      | Input 2
---------------------------------------
       id | 02004C4F4F50 | 02004C4F4F50
     type | registration | data
    value | {empty}      | flow

但是对于我当前的解决方案,可选组 (value) 永远不会匹配。 也许有人有提示。

您可以使用 [^/]+ 模式(除 / 字符之外的任何 1+ 个字符)匹配子部分,并使编号捕获组而不是 value 命名捕获组可选,即(/(?<value>.+)?) => (?:/(?<value>.+))?(另外,您可以将捕获组变为 non-capturing,或使用 (?n) inline ExplicitCapture modifier 使所有捕获组都表现为 non-capturing)。

您可以使用

^client/(?<id>[^/]+)/box/(?<type>[^/]+)(?:/(?<value>[^/]+))?

the regex demo