简体   繁体   中英

Javascript: equivalent regex for negative lookbehind?

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!

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'")

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++ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM