tags:

views:

35

answers:

3

Hello all,

Given the following string:

"<head></head><body>{"filesize":55312,"success":false,"msg":"incorrect-captcha-sol"}<div firebugversion="1.5.4" style="display: none;" id="_firebugConsole"></div></body>"

I need to extract the JSON string as follows:

{"filesize":55312,"success":false,"msg":"incorrect-captcha-sol"}

How should I do this?

Thank you

+1  A: 
json = str.match(/([^<]+)/)[1];
Delan Azabani
+1  A: 

A regular expression like

({[^}]+})

would work.

Try it out using RegExr.

cofiem
+1  A: 
 json = str.match(/(\{[^}]+\})/)[1];
pleasedontbelong
Hello,May you tell me why we have to use [1] here?I debug the code and it seems thatstr.match(/(\{[^}]+\})/)[0] is same as str.match(/(\{[^}]+\})/)[1]?Thank you
q0987
was my mistake :P... the match function returns an array of the elements that matched the regular expresion... because there was only one match it didn't matter, you can even delete the []you might want to look at this http://www.w3schools.com/jsref/jsref_match.asp
pleasedontbelong
Hello pleasedontbelong,it is strange that the first element of the returned array contains the same value as that of second element.When I search Google, I also see lots of example with [1].Really have no clues here.Thank you
q0987
The first element contains the full match, the second element is the capture group. In this case they are the same but they may not be. Note: because they are the same you might as well just do: `/\{[^}]+\}/`. But they may not be, for example if your intention is to instead match the value of filesize then: `/\{[^}]*filesize":[^}]*(\d+)[^}]*\}/` will match the whole json string as the first element and the string `"55312"` as the second element.
slebetman