I'm trying to get a regex that will find a double quoted strings within a double quoted string. For example:
"some text "string 1" and "another string" etc"
I would like to pick out "string 1" and "another string".
I got as far as \"[^\"]*\"
but this will match "some text " in the example. I basically need to ignore the first and last quotes and match within that.
Edit: The example mentioned doesn't have literal quotes surrounding it, but it is a Javascript string. The example regex is matching the entire string first. My Javascript is as follows.
var string = 'some "text" etc';
var pattern = new RegExp('\"[^\"]*\"/g');
var result = pattern.exec(string);
console.log("result: ", string);
// some "text" etc
I'm trying to get a regex that will find a double quoted strings within a double quoted string. For example:
"some text "string 1" and "another string" etc"
I would like to pick out "string 1" and "another string".
I got as far as \"[^\"]*\"
but this will match "some text " in the example. I basically need to ignore the first and last quotes and match within that.
Edit: The example mentioned doesn't have literal quotes surrounding it, but it is a Javascript string. The example regex is matching the entire string first. My Javascript is as follows.
var string = 'some "text" etc';
var pattern = new RegExp('\"[^\"]*\"/g');
var result = pattern.exec(string);
console.log("result: ", string);
// some "text" etc
So it could be my implementation of regex in Javascript that is the problem.
Share Improve this question edited Jan 19, 2017 at 20:29 Bryan asked Jan 19, 2017 at 20:12 BryanBryan 1,0052 gold badges8 silver badges18 bronze badges 3 |2 Answers
Reset to default 21Don't escape the "
. And just look for the text between quotes (in non greedy mode .*?
) like:
var string = 'some text "string 1" and "another string" etc';
var pattern = /".*?"/g;
var current;
while(current = pattern.exec(string))
console.log(current);
This works also:
var s = "\"some text \"string 1\" and \"another string\" etc\"" ""some text "string 1" and "another string" etc""
s.match(/(?!^)".*?"/g)
Result: [""string 1"", ""another string""]
The negative look ahead will not match the first quote because it's at the beginning, causing all others to match, ignoring the last one, since it doesn't have another quote following. This assumes there won't be any white space before the first quote of course.
var result = string.replace(/^"+|"+$/g, '').match(/"[^"]*"/g)
. Besides, in your code, you just print the input string, not the regex result. – Wiktor Stribiżew Commented Jan 19, 2017 at 20:34