我有一个像这样的字符串:
a b c a b " a b " b a " a "
我如何匹配每一个a
不是由以下分隔的字符串的一部分"
?我想匹配这里粗体的所有内容:
a bc a乙“乙”乙a " a "
我想替换这些匹配项(或者通过用空字符串替换它们来删除它们),因此删除匹配的带引号的部分将不起作用,因为我希望它们保留在字符串中。我正在使用红宝石。
假设引号正确平衡并且没有转义引号,那么很简单:
result = subject.gsub(/a(?=(?:[^"]*"[^"]*")*[^"]*\Z)/, '')
这取代了所有a
s 为空字符串当且仅当匹配项前面有偶数个引号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)/, '')
这本质上与上面的正则表达式相同,只是替换(?:\\.|[^"\\])
for [^"]
:
(?: # Match either...
\\. # an escaped character
| # or
[^"\\] # any character except backslash or quote
) # End of alternation
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)