我有这样一个字符串:
a b c a b " a b " b a " a "
如何匹配不是由 "
分隔的字符串的一部分的每个 a
?我想匹配此处加粗的所有内容:
a bc a b " ab " b a " a "
我想替换那些匹配项(或者更确切地说,通过用空字符串替换它们来删除它们),因此删除引用的匹配部分将不起作用,因为我希望它们保留在字符串中。我正在使用 Ruby。
最佳答案
假设引号正确平衡并且没有转义引号,那么很容易:
result = subject.gsub(/a(?=(?:[^"]*"[^"]*")*[^"]*\Z)/, '')
当且仅当匹配的 a
前面有偶数个引号时,这会将所有 a
替换为空字符串。
解释:
a # Match a
(?= # only if it's followed by...
(?: # ...the following:
[^"]*" # any number of non-quotes, followed by one quote
[^"]*" # the same again, ensuring an even number
)* # any number of times (0, 2, 4 etc. quotes)
[^"]* # followed by only non-quotes until
\Z # the end of the string.
) # End of lookahead assertion
如果您可以在引号内转义引号 (a "length: 2\""
),它仍然可行,但会更复杂:
result = subject.gsub(/a(?=(?:(?:\\.|[^"\\])*"(?:\\.|[^"\\])*")*(?:\\.|[^"\\])*\Z)/, '')
这在本质上与上面的正则表达式相同,只是将 (?:\\.|[^"\\])
替换为 [^"]
:
(?: # Match either...
\\. # an escaped character
| # or
[^"\\] # any character except backslash or quote
) # End of alternation
关于ruby - 如何匹配不在两个特殊字符之间的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502598/