问题描述
我需要一个正则表达式,匹配所有出现在引号((
)之前的两个引号(''
).我对括号做了一个负面的展望,后跟了一个引号.但是为什么这不起作用:
I need a regex matching all occurrences of two quotes (''
) not preceded by opening bracket ((
). I did a negative lookahead for the bracket followed by a quote. But why is this not working:
/(?!\()''/g
例如使用该字符串
(''test''test
它应该匹配第二个匹配项,但不匹配第一个匹配项,但它匹配两个匹配项.
It should match the second occurrence but not the first one but it matches both.
当我使用完全相同的解决方案但检查换行而不是括号时,它工作正常:
When I use exactly the same solution but with check for new line instead of bracket it works fine:
/(?!^)''/g
使用此字符串:
''test''test
它仅按预期匹配第二次出现.
It matches as expected only second occurrence.
在此处
推荐答案
即使您需要处理连续双撇号,
var output = "''(''test'''''''test".replace(/(\()?''/g, function($0, $1){
return $1 ? $0 : 'x';
});
document.body.innerHTML = output;
在这里,/(\()?''/g
正则表达式搜索带(
且不带(
的所有匹配项,但是在replace回调方法内部,我们检查第1组匹配项.如果第1组匹配,并且不为空,则将整个匹配用作替换文本($0
代表整个匹配值),如果不匹配(在''
之前没有(
),则只需插入替换.
Here, the /(\()?''/g
regex searches for all matches with the (
and without, but inside the replace callback method, we check for the Group 1 match. If Group 1 matched, and is not empty, we use the whole match as the replacement text ($0
stands for the whole match value) and if it is not (there is no (
before ''
) we just insert the replacement.
这篇关于匹配两个不带括号的引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!