theycallmemorty
theycallmemorty

Reputation: 12962

Javascript Regular Expression for multi-line string enclosed in quotes, possibly containing quotes

I would like to write a javascript regular expression that will match match multi-line strings contained in quotes that possibly also contain quotes. The final quote will be terminated with a comma.

For example:

"some text between the quotes including " characters",

This sting starts with a ", ends with ", and contains " characters.

How do I get this to work?

I guess the real question is How do i match a multi-line string that starts with " and ends with ",??

Upvotes: 1

Views: 963

Answers (3)

maerics
maerics

Reputation: 156434

Using a regular expression will be really tricky, I would try something like this:

var getQuotation = function(s) {
  var i0 = s.indexOf('"')
    , i1 = s.indexOf('",');
  return (i0 && i1) ? s.slice(i0+1, i1) : undefined;
};

var s = "He said, \"this is a test of\n" +
        "the \"emergency broadcast\" system\", obviously.";
getQuotation(s); // => 'this is a test of
                 //     the "emergency broadcast" system'

Upvotes: 1

Lepidosteus
Lepidosteus

Reputation: 12037

Doesn't a simple match() work ? You also need to use the \s\S trick to make the dot include line breaks (actually, that makes it accept every single characters ever):

var str = "bla bla \"some text between the quotes \n including \" characters\", bla bla";
var result = str.match(/"([\s\S]+)",/);
if (result == null) {
 // no result was found
} else {
 result = result[1];
 // some text between the quotes
 // including " characters
}

Upvotes: 3

kennytm
kennytm

Reputation: 523264

Match many non-", or " not followed by ,:

/"((?:[^"]|"(?!,))*)",/

or use lazy quantifier:

/"([\0-\uffff]*?)",/

Upvotes: 1

Related Questions