正则表达式匹配的引号字符串列表-未引号

时间:2020-03-06 14:51:41  来源:igfitidea点击:

在Javascript中,以下内容:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);

产生"快速","棕狐","跳跃","懒狗"

我希望每个匹配的元素都没有被引用:快速的棕狐狸跳过那只懒狗

什么正则表达式将执行此操作?

解决方案

我们可以使用Javascript replace()方法将其删除。

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';

var result = test.replace(/"/, '');

除了消除双引号之外,还有更多的功能吗?

这是一种方法:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.replace(/"(.*?)"/g, "");
alert(result);

这似乎可行:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/[^"]+(?=(" ")|"$)/g);
alert(result);

注意:这不匹配空元素(即"")。另外,它在不支持JavaScript 1.5的浏览器中也不起作用(超前功能是1.5的功能)。

有关更多信息,请参见http://www.javascriptkit.com/javatutors/redev2.shtml。

它不是一个正则表达式,而是两个更简单的正则表达式。

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';

var result = test.match(/".*?"/g);
// ["the quick","brown fox","jumps over","the lazy dog"]

result.map(function(el) { return el.replace(/^"|"$/g, ""); });
// [the quick,brown fox,jumps over,the lazy dog]

这是我将在actionscript3中使用的内容:

var test:String = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result:Array = test.match(/(?<=^"| ").*?(?=" |"$)/g);
for each(var str:String in result){
    trace(str);
}

grapefrukt的答案也可以。我会用大卫的变体

match(/[^"]+(?=("\s*")|"$)/g)

因为它可以正确处理字符串之间的任意数量的空格和制表符,而这正是我所需要的。