-1

Im trying to pass the following regex to javascript but I couldn't achieve passing it. I was the entire afternoon trying to successfully use it for my project, but sadly I couldn't find the way to make this work. Here's the link of the regex: https://regex101.com/r/lF0fI1/272

Regex: ((?<![\\])['"])((?:.(?!(?<![\\])\1))*.?)\1

Test string: [1, "c", "[\"asd\" , 2]"]

What I want to achive is to get outer quotes of a given string.

The regex was taken from here: https://www.metaltoad.com/blog/regex-quoted-string-escapable-quotes

Joaco Terniro
  • 115
  • 1
  • 2
  • 13

1 Answers1

0

If you only need to escape double quotes you can use this JavaScript compatible pattern:

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

It matches your sample string as required. Single quotes are disregarded.

Code sample:

const regex = /"(?:[^"\\]|\\.)*"/g;
const str = `[1, "c", "[\\"asd\\" , 2]", "['fgh' , 3]"]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

https://regex101.com/r/ylGzh4/2

wp78de
  • 18,207
  • 7
  • 43
  • 71