正则表达式 - 匹配单词集

时间:2012-07-16 09:22:38

标签: javascript regex

在JavaScript中,如何使用正则表达式从['John Smith', 'Jane Doe'] "John Smith - Jane Doe"获取- \ / , + * : ;可以是任何分隔符(new RegExp('[a-zA-Z]+[^\/|\-|\*|\+]', 'g'))等等? 使用["John ", "Smith ", "Jane ", "Doe"]只会给我{{1}}

2 个答案:

答案 0 :(得分:2)

试试这个,没有正则表达式:

var arr = str.split(' - ')

修改

多个分隔符:

var arr = str.split(/ [-*+,] /)

答案 1 :(得分:1)

如果要匹配多个单词,则需要在角色类中添加空格。我认为/[ a-zA-Z]+/g之类的内容会成为一个起点,与execString#match重复使用,如下所示:Live copy | source

var str = "John Smith - Jane Doe";
var index;
var matches = str.match(/[ a-zA-Z]+/g);
if (matches) {
  display("Found " + matches.length + ":");
  for (index = 0; index < matches.length; ++index) {
    display("[" + index + "]: " + matches[index]);
  }
}
else {
  display("No matches found");
}

但是非常有限,大量的名字都有AZ以外的字符,你可能想要反转你的逻辑并使用一个否定的类(/[^...]/g,其中{{1} }是可能的分隔符字符列表。你不想在寒冷中离开“ElizabethPeña”或“Gerard't Hooft”! : - )