Regex 不在引号之间时查找值
使用JavaScript和regex,我希望在每个%20上拆分一个不在引号内的字符串,例如:Regex 不在引号之间时查找值,regex,Regex,使用JavaScript和regex,我希望在每个%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%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 "}
但我的正则表达式似乎已经不足以构建表达式。谢谢你的帮助 试试看:
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);
}
}
一种使用替换方法但不使用替换结果的方法。其思想是在每次出现时使用闭包填充结果变量:
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);
您可以尝试使用以%20作为分隔符的CSV解析器。我认为可以下载用JS编写的CSV解析器。
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);