以下作品:
\[(?:\\[\[\]]|[^\[\]])*]
看到它工作:http ://www.rubular.com/r/cAajtm2wxw
解释:
\[ # opening bracket
(?: # start of non-capturing group (repeat zero or more times)
\\[\[\]] # backslash followed by [ or ]
| # OR
[^\[\]] # any character except [ or ]
)* # end of non-capturing group
] # closing bracket
请注意,这不是很安全,因为在像[ one \\[ two ] three ]
反斜杠这样的字符串中被转义了,所以在 之前的反斜杠[
不应该转义它。
要解决此问题,您可以使用以下内容:
\[(?:(?<!\\)(?:\\\\)*\\[\[\]]|[^\[\]])*]
这会将原始正则表达式中的单个转义反斜杠更改\\
为以下正则表达式,该正则表达式检查奇数个反斜杠:
(?<!\\) # fail if previous character is a backslash
(?:\\\\)* # some even number of backslashes
\\ # one more backslash to make it odd
http://www.rubular.com/r/BhQzLQpyB9