2011-01-21 253 views
0

在JavaScript中,我想要用'y'提取單詞列表結尾。使用正則表達式從字符串中提取字

代碼以下,

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; 

str.match(/(\w+)y\W/g); 

結果是一個數組

["simply ", "dummy ", "industry.", "industry'", "dummy ", "galley ", "only ", "essentially ", "recently "] 

所以,我的問題是, 我可以使用正則表達式得到一個單詞列表,而 'Y' 字。 結果單詞列表應該是這樣的,

["simpl ", "dumm ", "industr.", "industr'", "dumm ", "galle ", "onl ", "essentiall", "recentl"] 

/(\w+)y\W/g不起作用。

+1

你應該更新你的最後一個問題,使其更清晰,而不是發佈另一個**非常相似的! – 2011-01-21 07:09:55

回答

4

你需要什麼叫做look-ahead assertion:在(?=x)意味着在這場比賽前必須匹配x的人物,但不捕獲它們。

var trimmedWords = wordString.match(/\b\w+(?=y\b)/g); 
0

我認爲你正在尋找\b(\w)*y\b。 \ b是一個字詞分隔符。 \ w將匹配任何單詞字符,而y將指定它的結尾字符。然後你抓住\ w並排除y。

* 編輯我半收回那句話。如果你正在尋找「industr」。 (包括期間),這是行不通的。但我會玩,看看我能想出什麼。

1

這裏是一個辦法做到這一點:

var a = [], x; 
while (x = /(\w+)y\W/g.exec(str)) { 
    a.push(x[1]); 
} 

console.log(a); 
//logs 
["simpl", "dumm", "industr", "industr", "dumm", "galle", "onl", "essentiall", "recentl"] 
相關問題