Skip to content

string by spaces but ignore spaces in quotation marks

正規表現でダブルクオートで囲まれているところはそのまま取り出したい https://stackoverflow.com/questions/48142763/split-string-by-spaces-but-ignore-spaces-in-quotation-marks

var
/* The string. */
string = 'apples bananas "apples and bananas" pears "apples and bananas and pears"',
/* The regular expression. */
regex = /"[^"]+"|[^\s]+/g,
/* Use 'map' and 'replace' to discard the surrounding quotation marks. */
result = string.match(regex).map(e => e.replace(/"(.+)"/, "$1"));
console.log(result);
>>> match = re.findall(r'"[^"]+"|[^\s]+', 'apples bananas "apples and bananas" pears "apples and bananas and pears"')
>>> match
['apples', 'bananas', '"apples and bananas"', 'pears', '"apples and bananas and pears"']