使用正则表达式

时间:2016-10-05 14:39:27

标签: javascript regex

我试图找到包含特定单词的句子。 我定义了一个以下列字符开头和结尾的句子:. ! ?

var str = "Hello, how is it going. This is the bus we have to take!";
var regex = /[^.?!]*(?:[.?,\s!])(bus)(?=[\s.?!,])[^.?!]*[.?!]/igm;

var result = regex.exec(str);


output : `This is the bus we have to take!`

现在,当我尝试找到包含单词hello的句子时,我遇到了麻烦,因为它正在启动句子。我怎么能改变我的正则表达式来包括那个案子?我不习惯正则表达式而且很难进入它,即使我的眼睛下有文档!

1 个答案:

答案 0 :(得分:1)

请记住,将文本拆分为语言句是一项非常具体,困难的任务,通常在NLP包的帮助下执行。

如果您想限制遵循您的句子定义的特定字符串:

  • /[.?!]/ regex
  • 分开
  • 检查条目是否包含RegExp#test()的子字符串,因为您需要不区分大小写的检查



var str = "Hello, how is it going. This is the bus we have to take!";
var chunks = str.split(/[.?!]/).filter(function(n) {
  return /hello/i.test(n);
});
console.log(chunks);




请注意,要检查整个单词,您可以使用/\bhello\b/i/(?:^|\s)hello(?!\S)/i regexps,具体取决于其他要求。