0

第一次发帖,请温柔点。我的目标是匹配由逗号分隔的第一组括号内的一组字符(数字除外),同时忽略空格。诀窍是不匹配嵌套在另一组括号中的逗号。我的解决方案似乎有效,所以我想分享我的解决方案,并就任何其他更好的解决方案获得意见。

我的示例输入字符串是:

test[ [a], b1 ,  1,2 , cc[nn[ 99],oo[ g  , l]],dd].test2[ ee , 22 ]

期望的匹配:

1. "[a]"
2. "b1"
3. "cc[nn[ 99],oo[ g  , l]]"
4. "dd"
5. "ee"

解决方案:

Regex regexObj = new Regex(
@"(?<=[,\[]\s*)  (?# Match must start with, but not include, opening bracket or comma)
  (?![0-9])      (?# Do not match if followed by a number)
  (?>            (?# Start atomic group, do not backtrack inside the match)
   (?(DEPTH)     (?#  Check IF inside an un-closed bracket group THEN)
    [^\[\]]      (?#   match any char except brackets)
   |             (?#  ELSE closed)
    [^\s,\[\]])  (?#   delimit by comma)
  |              (?# OR)
   (?'DEPTH'\[)  (?#  Match open bracket and increase DEPTH count)
  |              (?# OR)
   (?'-DEPTH'\]) (?#  Match closed bracket and decrease DEPTH count)
  )*             (?# Continue atomic group)
 (?(DEPTH)(?!))  (?# Ensure the match has a balanced set of brackets)
 (?=\s*[,\]])    (?# Match must end with a comma or closing bracket)",
RegexOptions.IgnorePatternWhitespace);

我工作的例子在这里找到C# Regex - How to remove multiple pair of parentheses from string

4

0 回答 0