Regex to match all instances not inside quotes Regex to match all instances not inside quotes javascript javascript

Regex to match all instances not inside quotes


Actually, you can match all instances of a regex not inside quotes for any string, where each opening quote is closed again. Say, as in you example above, you want to match \+.

The key observation here is, that a word is outside quotes if there are an even number of quotes following it. This can be modeled as a look-ahead assertion:

\+(?=([^"]*"[^"]*")*[^"]*$)

Now, you'd like to not count escaped quotes. This gets a little more complicated. Instead of [^"]* , which advanced to the next quote, you need to consider backslashes as well and use [^"\\]*. After you arrive at either a backslash or a quote, you need to ignore the next character if you encounter a backslash, or else advance to the next unescaped quote. That looks like (\\.|"([^"\\]*\\.)*[^"\\]*"). Combined, you arrive at

\+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)

I admit it is a little cryptic. =)


Azmisov, resurrecting this question because you said you were looking for any efficient alternative that could be used in JavaScript and any elegant solutions that would work in most, if not all, cases.

There happens to be a simple, general solution that wasn't mentioned.

Compared with alternatives, the regex for this solution is amazingly simple:

"[^"]+"|(\+)

The idea is that we match but ignore anything within quotes to neutralize that content (on the left side of the alternation). On the right side, we capture all the + that were not neutralized into Group 1, and the replace function examines Group 1. Here is full working code:

<script>var subject = '+bar+baz"not+these+"foo+bar+';var regex = /"[^"]+"|(\+)/g;replaced = subject.replace(regex, function(m, group1) {    if (!group1) return m;    else return "#";});document.write(replaced);

Online demo

You can use the same principle to match or split. See the question and article in the reference, which will also point you code samples.

Hope this gives you a different idea of a very general way to do this. :)

What about Empty Strings?

The above is a general answer to showcase the technique. It can be tweaked depending on your exact needs. If you worry that your text might contain empty strings, just change the quantifier inside the string-capture expression from + to *:

"[^"]*"|(\+)

See demo.

What about Escaped Quotes?

Again, the above is a general answer to showcase the technique. Not only can the "ignore this match" regex can be refined to your needs, you can add multiple expressions to ignore. For instance, if you want to make sure escaped quotes are adequately ignored, you can start by adding an alternation \\"| in front of the other two in order to match (and ignore) straggling escaped double quotes.

Next, within the section "[^"]*" that captures the content of double-quoted strings, you can add an alternation to ensure escaped double quotes are matched before their " has a chance to turn into a closing sentinel, turning it into "(?:\\"|[^"])*"

The resulting expression has three branches:

  1. \\" to match and ignore
  2. "(?:\\"|[^"])*" to match and ignore
  3. (\+) to match, capture and handle

Note that in other regex flavors, we could do this job more easily with lookbehind, but JS doesn't support it.

The full regex becomes:

\\"|"(?:\\"|[^"])*"|(\+)

See regex demo and full script.

Reference

  1. How to match pattern except in situations s1, s2, s3
  2. How to match a pattern unless...


You can do it in three steps.

  1. Use a regex global replace to extract all string body contents into a side-table.
  2. Do your comma translation
  3. Use a regex global replace to swap the string bodies back

Code below

// Step 1var sideTable = [];myString = myString.replace(    /"(?:[^"\\]|\\.)*"/g,    function (_) {      var index = sideTable.length;      sideTable[index] = _;      return '"' + index + '"';    });// Step 2, replace commas with newlinesmyString = myString.replace(/,/g, "\n");// Step 3, swap the string bodies backmyString = myString.replace(/"(\d+)"/g,    function (_, index) {      return sideTable[index];    });

If you run that after setting

myString = '{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}';

you should get

{:a "ab,cd, efg" :b "ab,def, egf," :c "Conjecture"}

It works, because after step 1,

myString = '{:a "0", :b "1", :c "2"}'sideTable = ["ab,cd, efg", "ab,def, egf,", "Conjecture"];

so the only commas in myString are outside strings. Step 2, then turns commas into newlines:

myString = '{:a "0"\n :b "1"\n :c "2"}'

Finally we replace the strings that only contain numbers with their original content.