我需要像下面这样拆分一个字符串,以空格作为分隔符。但是引号内的任何空格都应该保留。有两种情况需要工作
案例一
research library "not available" author:"Bernard Shaw"
到
research
library
"not available"
author:"Bernard Shaw"
案例2
research library "not available" author:Bernard
到
research
library
"not available"
author:Bernard
我正在尝试使用 Javascript 和正则表达式来做到这一点。
var splitArray = query_string.match(/([^\s]*\"[^\"]+\")|\w+/g);
案例 1 按要求工作,但案例 2 产生如下结果
research
library
"not available"
author
Bernard
我需要这两种情况才能使用一个正则表达式。任何想法表示赞赏。
最佳答案
[^"\s]+(?:"[^"]+")?|"[^"]+"
解释:
[^"\s]+ # One or more non-space/non-quote characters
(?:"[^"]+")? # optionally followed by a quoted string
| # or
"[^"]+" # just a quoted string.
假设带引号的字符串中没有转义引号。
关于javascript正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922295/