Reputation: 519
I want to write a regular expression that will captures all double quotes " in a string, except for those that are escaped.
For example, in the following String will return the first quote only:
"HELLO\"\"\"
but the following one will return 3 matches:
"HELLO\"\""\""
I have used the following expression, but since in JavaScript there is no negative lookbehind I am stuck:
(?<!\\)"
I have looked at similar questions but most provide a programmatic interface. I don't want to use a programmatic interface because I am using Ace editor and the simplest way to go around my problem is to define this regex.
I suppose there is no generic alternative, since I have tried the alternatives proposed to the similar questions, but non of them exactly matched my case.
Thanks for your answers!
Upvotes: 0
Views: 1681
Reputation: 16118
The code I assume you are trying to run:
while ( matcher = /(?<!\\)"/g.exec(theString) ) {
// do stuff. matcher[0] is double quotes (that don't follow a backslash)
}
In JavaScript, using this guide to JS lookbehinds:
while ( matcher = /(\\)?"/g.exec(theString) ) {
if (!matcher[1]) {
// do stuff. matcher[0] is double quotes (that don't follow a backslash)
}
}
This looks for double quotes ("
) that optionally follow a backslash (\
) but then doesn't act when it actually does follow a backslash.
If you were merely trying to count the number of unescaped double-quotes, the "do stuff" line could be count++
.
Upvotes: 0
Reputation: 48807
You can use this workaround:
(^|[^\\])"
"
only if preceded by any char but a \
or the beginning of the string (^
).
But be careful, this matches two chars: the "
AND the preceding character (unless in the start-of-the-string case). In other words, if you wan't to replace all these "
by '
for example, you'll need:
theString.replace(/(^|[^\\])"/g, "$1'")
Upvotes: 1