2011-01-21 171 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"] 
相关问题