C#正则表达式原子打开和关闭支架

时间:2019-11-24 04:34:50

标签: c# regex regex-group

我有以下一个占位符,我正在尝试使用Atomic组来成对捕获双开括号和右括号:

  

{{(?> {{(?)|}}(<-DEPTH>)| [^ {}])*}}(?(DEPTH)(?!))

     

我是{{name}},我有{{scales}:红色{{metallic_scales}:有光泽且闪闪发光的}}秤}}

可以肯定地说,我并没有取得多少成功。

所以我想要类似的东西:

  1. {{name}}
  2. {{scales}:红色{{metallic_scales}:有光泽的玻璃}}秤}}
  3. {{metallic_scales}:闪闪发亮}}

1 个答案:

答案 0 :(得分:0)

您可以使用

(?=                    # Start of a positive lookahead to enable overlapping matches
  (?<results>          # The group storing the results
    {{                 # {{ (left-hand delimiter)
      (?>              # Start of an atomic group
        (?!{{|}}).|    # Any char not starting {{ or }} char sequence, or
        {{(?<DEPTH>)|  # {{ and a value pushed on to DEPTH group stack, or
        }}(?<-DEPTH>)  # }} and a value popped from the DEPTH group stack
      )*               # Zero or more repetitions of the atomic group patterns
    }}                 # }} substring
    (?(DEPTH)(?!))     # Conditional construct failing the match if DEPTH stack is not empty
  )                    # End of the results group
)                      # End of the lookahead

请参见regex demo

C#声明:

Regex reg = new Regex(@"
    (?=                  # Start of a positive lookahead to enable overlapping matches
      (?<results>          # The group storing the results
        {{                 # {{ (left-hand delimiter)
          (?>              # Start of an atomic group
            (?!{{|}}).|    # Any char not starting {{ or }} char sequence, or
            {{(?<DEPTH>)|  # {{ and a value pushed on to DEPTH group stack, or
            }}(?<-DEPTH>)  # }} and a value popped from the DEPTH group stack
          )*               # Zero or more repetitions of the atomic group patterns
        }}                 # }} substring
        (?(DEPTH)(?!))     # Conditional construct failing the match if DEPTH stack is not empty
      )                    # End of the results group
    )                      # End of the lookahead", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
var results = reg.Matches(text).Cast<Match>().Select(x => x.Groups["results"].Value);