Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp matching of list of quotes strings - unquoted

in Javascript, the following:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);

yields "the quick","brown fox","jumps over","the lazy dog"

I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog

what regexp will do this?

like image 964
Scott Evernden Avatar asked Sep 29 '08 05:09

Scott Evernden


3 Answers

This seems to work:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/[^"]+(?=(" ")|"$)/g);
alert(result);

Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature).

See http://www.javascriptkit.com/javatutors/redev2.shtml for more info.

like image 183
David Crow Avatar answered Oct 31 '22 19:10

David Crow


It is not one regexp, but two simpler regexps.

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';

var result = test.match(/".*?"/g);
// ["the quick","brown fox","jumps over","the lazy dog"]

result.map(function(el) { return el.replace(/^"|"$/g, ""); });
// [the quick,brown fox,jumps over,the lazy dog] 
like image 4
jfs Avatar answered Oct 31 '22 18:10

jfs


grapefrukt's answer works also. I would up using a variation of David's

match(/[^"]+(?=("\s*")|"$)/g)

as it properly deals with arbitrary amounts of white space and tabs tween the strings, which is what I needed.

like image 1
Scott Evernden Avatar answered Oct 31 '22 18:10

Scott Evernden