在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
不起作用。
答案 0 :(得分:4)
您需要所谓的look-ahead assertion:(?=x)
表示此匹配前的字符必须与x
匹配,但不会捕获它们。
var trimmedWords = wordString.match(/\b\w+(?=y\b)/g);
答案 1 :(得分: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"]
答案 2 :(得分:0)
我认为你正在寻找\b(\w)*y\b
。 \ b是一个单词分隔符。 \ w将匹配任何单词字符,而y指定它的结束字符。然后你抓住\ w并排除y。
* 编辑我半回来了。如果你正在寻找“industr”。 (包含期限)这不起作用。但是我会玩,看看我能想出什么。