问题描述
我正在寻找匹配任意字符串中未转义引号的正则表达式,但不匹配已转义的引号,以便我可以转义未转义的引号.我尝试修改我发现的任何类似解决方案,但没有完全满足我的需求.
I'm looking for a regex that matches unescaped quotes in an arbitrary string, but not quotes that are already escaped so I can escape the unescaped quotes. I tried to modify any similar solutions I found but nothing captured exactly what I need.
正则表达式应该
abc"asd # match
abc\"asd # not match
abc\\"asd # match
abc\\\"asd # not match
abc\\\\"asd # match
所以基本上匹配以偶数个反斜杠(包括零)开头的任何引号,但不匹配以奇数个反斜杠开头的任何引号.
so basically match any quotes preceded by an even number of backslashes (including zero) but not match any quotes preceded by an odd number of backslashes.
有人可以帮忙吗?
PS:我想用 ruby 来做这个
PS: I want to do this in ruby
推荐答案
你可以使用这个:
(?<!\\)(?:\\{2})*\K"
(?<!\\)
检查之前没有反斜杠(负向后视)
(?<!\\)
checks there is no backslash before (negative lookbehind)
(?:\\{2})*
匹配所有偶数个反斜杠
(?:\\{2})*
matches all even numbers of backslashes
\K
从匹配结果中删除左侧的所有内容(此处为反斜杠)
\K
removes all on the left from the match result (the backslashes here)
这篇关于正则表达式匹配未转义的引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!