1

I have following text:

response={\n  &quot;status&quot; : &quot;ERROR&quot;,\n &quot;message&quot; : &quot;<ERROR Mes$@ge can be anything>&quot;,\n &quot;responseMessage&quot; : &quot;Response&quot;,\n &quot;reason&quot; : &quot;REASON&quot;,\n  }

I want to extract this part from the above text -

&quot;message&quot; : &quot;<ERROR Mes$@ge can be anything>&quot;

Please note - error message can have any chars including special chars.

I have written following regex -

\&quot;message\&quot; \: \&quot;.+\&quot;,\\n

However, it extracts till the last occurrence of &quot;,\n.

I think somehow I should count the occurrences of &quot; in the regex.

Need help with the Regex.

Nilesh Barai
  • 1,312
  • 8
  • 22
  • 48
  • If you don't need regex and are just trying to split it you can do this `string.split(",\n").map(a => {return a.trim()}).filter(a => {return a.includes(""message"")});` which is more human readable. http://jsfiddle.net/link2twenty/Lqfy9x23/ – Andrew Bone Jun 14 '18 at 13:24

2 Answers2

0

You are using the greedy matcher .+, you need to use the non-greedy matcher .+?

e.g.

\&quot;message\&quot; \: \&quot;.+?\&quot;,\\n
                                  ^
Jonathan Benn
  • 2,908
  • 4
  • 24
  • 28
0

Here's what I have done.

Used (|) as an OR statement to separate &quot; and \n.

I escaped \n with \\n

let str = "response={\n  &quot;status&quot; : &quot;ERROR&quot;,\n &quot;message&quot; : &quot;<ERROR Mes$@ge can be anything>&quot;,\n &quot;responseMessage&quot; : &quot;Response&quot;,\n &quot;reason&quot; : &quot;REASON&quot;,\n  }"

let replacedStr = str.replace(/(&quot;|\\n)/g,'"');

console.log(replacedStr);
Alex
  • 2,164
  • 1
  • 9
  • 27