简体   繁体   English

正则表达式 - 带替换的可选组

[英]Regex - Optional Group With Replacement

I need to capture up to four digits, as follows, in a named group:我需要在命名组中捕获最多四位数字,如下所示:

    123       -> 123
    2357      -> 2357
    123 (11X) -> 11
    235 (7Y)  -> 7

As you can see, the bracketed number and letter is optional.如您所见,括号中的数字和字母是可选的。 Though there appear to be similar questions on the forum, my limited knowledge prevents me from adapting their solutions.虽然论坛上似乎有类似的问题,但我有限的知识使我无法调整他们的解决方案。

My initial attempt is, as follows:我的初步尝试如下:

(?<ABC>\d{0,4})?|\((?<DEF>\d{0,4})(?<GHI>[A-Za-z])\)

正则表达式可视化

Debuggex Demo seems to capture the groups I need, but how do I automatically choose the correct group in a replacement context - ABC or DEF depending on the input? Debuggex Demo似乎捕获了我需要的组,但是如何根据输入在替换上下文中自动选择正确的组 - ABC 或 DEF?

Do I need a 'branch reset' so that I can give groups 'ABC' and 'DEF' the same name and, if so, how do I implement it?我是否需要“分支重置”以便我可以为组“ABC”和“DEF”指定相同的名称,如果需要,我该如何实现?

Please advise?请指教?

经过多次反复试验,以下模式适用于 .NET [解决方案]:

    (?<ABC>\d{0,4}) ?\((?<ABC>\d{0,4})(?<GHI>[A-Za-z])?\)        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM