匹配右括号的正则表达式不在引号中

Dan*_*şar 6 .net regex

我正在尝试构建一个匹配字符串的正则表达式

1.) $(Something)
2.) $(SomethingElse, ")")
3.) $(SomethingElse, $(SomethingMore), Bla)
4.) $$(NoMatch) <-- should not match
5.) $$$(ShouldMatch) <-- so basically $$ will produce $
Run Code Online (Sandbox Code Playgroud)

在文本中.

编辑:单词Something,SomethingElse,NoMatch,ShouldMatch甚至可以是其他单词 - 它们是宏的名称.我试图匹配的字符串是"宏调用",它可以出现在文本中,应该用它们的结果替换.我需要正则表达式只是为了语法高亮.应突出显示完整的宏调用.3号目前不是那么重要.需要1号和2号才能工作.如果数字4和5不能像上面所写的那样工作,但是$(在a之后的任何一个$都不匹配,那就没关系了.

目前我有

(?<!\$)+\$\(([^)]*)\)
Run Code Online (Sandbox Code Playgroud)

$(如果没有前导$,哪个匹配任何匹配,如果我找不到另一种方法来应用$$结构,这可能没问题.

我想要完成的下一步是忽略结束括号,如果它在引号中.我怎么能实现这个目标?

编辑所以,如果我有一个像这样的输入

Some text, doesn't matter what. And a $(MyMacro, ")") which will be replaced.
Run Code Online (Sandbox Code Playgroud)

完整'$(MyMacro, ")")'将突出显示.

我已经有了这个表达方式

"(?:\\\\|\\"|[^"])*"
Run Code Online (Sandbox Code Playgroud)

报价包括报价转义.但我不知道如何应用这种方式来忽略它们之间的一切......

PS我正在使用.NET来应用正则表达式.这样平衡的团体将得到支持.我只是不知道如何应用这一切.

Qta*_*tax 5

您可以使用这样的表达式:

(?<! \$ )                     # not preceded by $
\$ (?: \$\$ )?                # $ or $$$
\(                            # opening (

(?>                           # non-backtracking atomic group
  (?>                         # non-backtracking atomic group
    [^"'()]+                  # literals, spaces, etc
  | " (?: [^"\\]+ | \\. )* "  # double quoted string with escapes
  | ' (?: [^'\\]+ | \\. )* '  # single quoted string with escapes
  | (?<open>       \( )       # open += 1
  | (?<close-open> \) )       # open -= 1, only if open > 0 (balancing group)
  )*
)

(?(open) (?!) )               # fail if open > 0

\)                            # final )
Run Code Online (Sandbox Code Playgroud)

可以引用如上。例如在 C# 中:

var regex = new Regex(@"(?x)    # enable eXtended mode (ignore spaces, comments)
(?<! \$ )                       # not preceded by $
\$ (?: \$\$ )                   # $ or $$$
\(                              # opening (

(?>                             # non-backtracking atomic group
  (?>                           # non-backtracking atomic group
    [^""'()]+                   # literals, spaces, etc
  | "" (?: [^""\\]+ | \\. )* "" # double quoted string with escapes
  | '  (?: [^'\\]+ | \\. )*  '  # single quoted string with escapes
  | (?<open>       \( )         # open += 1
  | (?<close-open> \) )         # open -= 1, only if open > 0 (balancing group)
  )*
)

(?(open) (?!) )                 # fail if open > 0

\)                              # final )
");
Run Code Online (Sandbox Code Playgroud)