不在引号之间找到值

时间:2014-05-30 14:40:34

标签: regex

使用JavaScript&正则表达式我想在每个%20上拆分不在引号内的字符串,例如:

Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"
//easy to read version: Here is "a statement " for Testing " The Values "
                                ______________             ______________

将返回

{"Here","is","a statement ","for","Testing"," The Values "}

但似乎我的正则表达式不再足以构建表达式。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

使用replace方法的方法,但不使用替换结果。我们的想法是在每次出现时使用闭包来填充结果变量:

var txt = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"';
var result = Array();

txt.replace(/%20/g, ' ').replace(/"([^"]+)"|\S+/g, function (m,g1) {
    result.push( (g1==undefined)? m : g1); });

console.log(result);

答案 1 :(得分:0)

试试:

var input  = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"',
    tmp    = input.replace(/%20/g, ' ').split('"'),
    output = []
;

for (var i = 0; i < tmp.length; i++) {
  var part = tmp[i].trim();
  if (!part) continue;

  if (i % 2 == 0) {
    output = output.concat(part.split(' '));
  } else {
    output.push(part);
  }
}

输出:

["Here", "is", "a statement", "for", "Testing", "The Values"]