Search code examples
javascriptregexdouble-quotessquare-bracketquotation-marks

How do I look in a string with text inside quotations, but ignoring anything inside brackets using regex?


For example my string is:

var str = 'Hello "Counts1 [ignore1] Counts2 [ignore2] Counts3 [ignore3] Count these too"';

How would I get everything inside the string that is inside quotations ignoring the characters inside the brackets?

So for example a regex to collect: "Counts1", "Counts2", "Counts3", "Count these too"

So far I only got:

var regex = /".*?"/g;

It outputs:

"Counts1 [ignore1] Counts2 [ignore2] Counts3 [ignore3]"

Solution

  • This should do it: /(?<="|\] )[\w ]+(?="| \[)/g

    Positive lookbehind (?<="|\] ) makes sure that [\w ]+ has either " or ] to the left.
    Positive lookahead (?="| \[) makes sure that [\w ]+ has either " or [ to the right.

    Demo