5

最终我试图改变这个:

var msg = '-m "this is a message" --echo "another message" test arg';

进入这个:

[
    '-m',
    'this is a message',
    '--echo',
    'another message',
    'test',
    'arg'
]

我不太确定如何解析字符串以获得所需的结果。这是我到目前为止所拥有的:

var msg = '-m "this is a message" --echo "another message" test arg';

// remove spaces from all quoted strings.
msg = msg.replace(/"[^"]*"/g, function (match) {
    return match.replace(/ /g, '{space}');
});

// Now turn it into an array.
var msgArray = msg.split(' ').forEach(function (item) {
    item = item.replace('{space}', ' ');
});

我认为这会奏效,但男人这样做似乎是一种反复无常和倒退的方式来完成我想要的。我相信你们有比在拆分之前创建占位符字符串更好的方法。

4

3 回答 3

5

使用 exec(),您可以使用不带引号的字符串:

var test="once \"upon a time\"  there was   a  \"monster\" blue";

function parseString(str) {
    var re = /(?:")([^"]+)(?:")|([^\s"]+)(?=\s+|$)/g;
    var res=[], arr=null;
    while (arr = re.exec(str)) { res.push(arr[1] ? arr[1] : arr[0]); }
    return res;
}

var parseRes= parseString(test);
// parseRes now contains what you seek
于 2013-03-14T23:13:37.373 回答
4

而不是 a split,您可以match

var msg = '-m "this is a message" --echo "another message" test arg';
var array = msg.match(/"[^"]*"|[^\s"]+/g);
console.log(array);

产生:

['-m',
  '"这是一条消息"',
  ' - 回声',
  '"另一条消息"',
  '测试',
  'arg']
于 2013-03-14T21:46:14.510 回答
1

很难猜测您更喜欢什么作为解决方案,但一种方法是用引号分割(假设没有嵌套引号),然后用空格分割每个备用项:

result = [];
msg.split("\"").map(function(v, i ,a){
    if(i % 2 == 0) {
        result = result.concat(v.split(" ").filter(function(v){
            return !v;
        }));
    } else {
        result.push(v);
    }
});

这是一个演示:http: //jsfiddle.net/eL7cc/

于 2013-03-14T21:40:54.477 回答