Bryan
Bryan

Reputation: 1005

Regex to find any double quoted string within a string

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.

Upvotes: 10

Views: 22746

Answers (2)

James Wilkins
James Wilkins

Reputation: 7388

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.

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Don'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);

Upvotes: 21

Related Questions