[英]Regex - Match sets of words
在JavaScript中,我將如何獲得['John Smith', 'Jane Doe']
從"John Smith - Jane Doe"
在那里-
可以是任意分隔符( \\ / , + * : ;
)等,使用正則表達式?
使用new RegExp('[a-zA-Z]+[^\\/|\\-|\\*|\\+]', 'g')
只會給我["John ", "Smith ", "Jane ", "Doe"]
試試這個,沒有正則表達式:
var arr = str.split(' - ')
編輯
多個分隔符:
var arr = str.split(/ [-*+,] /)
如果要匹配多個單詞,則需要在角色類中添加空格。 我認為/[ a-zA-Z]+/g
將是一個起點,與exec
重復使用或通過String#match
,如下所示: live copy | 資源
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
,其中...
是一個可能的分隔符字符列表)。 你不想在寒冷中離開“ElizabethPeña”或“Gerard't Hooft”! :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.