简体   繁体   English

使用正则表达式从字符串中提取单词

[英]Extract word from string using regex

In javascript, I want extract word list ends with 'y'. 在javascript中,我要提取单词列表以“ y”结尾。

code is following, 代码在后面,

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);

result is a array 结果是一个数组

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

so, my question is, Can I get a word list without 'y' character using regex. 因此,我的问题是,我可以使用正则表达式获取不带'y'字符的单词列表吗? the result word list should be like this, 结果单词列表应该是这样的,

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

/(\\w+)y\\W/g doesn't work. /(\\w+)y\\W/g不起作用。

您需要所谓的先行断言(?=x)表示此匹配项前面的字符必须与x匹配,但不要捕获它们。

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

Here is a way to do it: 这是一种方法:

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"]

I think you're looking for \\b(\\w)*y\\b . 我认为您正在寻找\\b(\\w)*y\\b The \\b is a word separator. \\ b是一个单词分隔符。 The \\w will match any word character, and the y to specify it's ending character. \\ w将匹配任何单词字符,而y则指定其结尾字符。 Then you grab the \\w and exclude the y. 然后,您抓住\\ w并排除y。

* EDIT I semi-take that back. * 编辑我将其收回。 If you're looking for "industr." 如果您正在寻找“行业”。 (with the period included) this will not work. (含期间)将不起作用。 but I'll play around and see what I can come up with. 但我会玩转,看看我能想到什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM