dhrubo_moy dhrubo_moy -3 years ago 141
Javascript Question

Regex: ignore the first and last occurrence of " but not the rest

I have three strings:

  1. {{"ErrorMsg: [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'blah'"}}

  2. {{"ErrorMsg: FATAL: role \"foobar\" does not exist\n"}}

  3. "{{\"param1\"}, {\"param2\"}}"

For the first 2 cases I want to get a 1-element array, while for the 3rd case I want to get a 2-element array (
['param1', 'param2']
). Following expression works for the first string:


but doesn't work for the second string because there are two more
inside. How should I make it work?

You can try it out here

Answer Source

You can use this regex:


Matches will be available in captured group #1 that you can extract using a while loop calling regex.exec(str) in the loop.

Updated RegEx Demo

RegEx Breakup:

{          # match {
\\?        # match \ optionally 
"          # match a double quote
([^}]+?)   # match any character that is not a } (lazy match)
(?=\\?"})  # lookahead to assert we have optional \ followed by "}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download