Javascript正则表达式转义引号(但不转义已转义的引号) [英] Javascript regex to escape quotes (but not escape already escaped quotes)

查看:67
本文介绍了Javascript正则表达式转义引号(但不转义已转义的引号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个JavaScript正则表达式,该正则表达式将转义单引号,但不应转义已经转义的单引号.

I am looking for a JavaScript regex which will escape single quotes but it should not escape single quotes which are already escaped.

推荐答案

理想情况下,您希望每个匹配都从上一个匹配结束的地方开始.否则,很容易与转义序列不同步.@outis的正则表达式接近,但是它无法转义'\\'中的第二个单引号.第一次匹配后,它必须匹配至少一个非反斜杠和一个单引号,而这是不能做到的.如果还有其他字符,它将跳过并在第二个单引号之后开始匹配.

Ideally, you want every match to start exactly where the previous match ended. Otherwise it's too easy to get out of sync with the escape sequences. @outis's regex comes close, but it fails to escape the second single-quote in '\\'. After the first match, it has to match at least one non-backslash and one single-quote, which it can't do. If there are any more characters, it skips ahead and starts matching after the second single-quote.

请尝试以下方法:

result = subject.replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, "$1\\'");

这是Friedl的展开循环"模式的示例:

This is an example of Friedl's "unrolled loop" pattern:

普通*(特殊普通*)*

[^'\\] * 是普通*"部分;它会吞除除单引号或反斜杠以外的任意数量的字符.如果下一个字符是反斜杠,则 \\.(特殊")将使用该字符,而下一个字符(反斜杠,单引号或其他字符)和 [^'\\] *再次接管.根据需要重复.

[^'\\]* is the "normal *" part; it gobbles up any number of characters other than single-quotes or backslashes. If the next character is a backslash, \\. ("special") consumes that and the next character (backslash, single-quote, or whatever) and [^'\\]* takes over again. Repeat as needed.

关键是正则表达式永远不会跳过,也不会回退.如果看到反斜杠,它会总是使用该斜杠和下一个字符,因此它永远不会失去同步.

The key point is that the regex never skips ahead and it never backtracks. If it sees a backslash, it always consumes that and the next character, so it never gets out of sync.

这篇关于Javascript正则表达式转义引号(但不转义已转义的引号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆