问题
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
for example with this string
(''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
With this string:
''test''test
It matches as expected only second occurrence.
Tested here
回答1:
Here is a solution that will work correctly even in case you need to handle consecutive double apostrophes:
var output = "''(''test'''''''test".replace(/(\()?''/g, function($0, $1){
return $1 ? $0 : 'x';
});
document.body.innerHTML = output;
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.
回答2:
It's bad that Javascript doesn't support lookback but there is a workaround.
try:
[^\(]('{2,2})
See https://regex101.com/r/gT5jR6/1
来源:https://stackoverflow.com/questions/36838311/match-two-quotes-not-preceded-by-opening-bracket