Matching string between first and last quote
I have a string that contains a JSON object. Problem is the object is being returned like this for some reason:
string (4345) "{ "blabla" : { "bleble"开发者_如何学运维 : "bloblo" } ...}"
I need to extract everything between the first and last quotation basicly so that I can then decode the object.
I tried this in javascript:
var myVar = myString.match(/\".+$\"/);
But it's not working. What's the appropriate RegEx for my problem?
So you know that (in your example) myString has your JSONed thing? Why not do:
var myVar = myString.substring(1, myString.length - 2);
If there's some other junk before or after your JSONed thing, I guess you could use the indexOf and lastIndexOf operations.
Also check out this question: Regex to validate JSON
In response to the question in the comment:
//So let's say we have this string
example = '"[ { "title": "event1", "start": "NOW", } ]"'
//So our example string has quote literals around the bits we want
//indexOf gives us the index of the " itself, so we should add one
//to get the character immediately after the "
first_nonquote_character = example.indexOf('"') + 1
//lastIndexOf is fine as is, since substring doesn't include the character
//at the ending index
last_nonquote_character = example.lastIndexOf('"')
//So we can use the substring method of the string object and the
//indices we created to get what we want
string_we_want = example.substring(first_nonquote_character, last_nonquote_character)
//The value in string_we_want is
//[ { "title": "event1", "start": "NOW", } ]
Hope that helps. BTW if your JSON is actually coming back with the ', } ]"' at the end of it and that's not a typo, you'd probably want to do a string.replace(/, } ]"$/, '}]').
You just need to get the group submatch:
/"(.*)"/.exec(myString)[1]
This regex worked for me (I tested it with Rubular):
/"(.+)"/
And you could use it like this:
var newString = oldString.replace(/"(.+)"/, "$1");
Where the parens are for capturing what's in between the quotation marks (because you didn't want them, right?).
Try this:
var newstr = oldstr.match(/"(.+)"/)[1];
精彩评论