我在这里发布了一个示例:http://codepen.io/ahamilton9/pen/hqmLc
这是JavaScript:
var content = 'This is my content which contains KEYWORD and should return seven words. ';
var regex = new RegExp('(?:(?:\w+\W*){0,3})' + 'keyword' + '(?:(?:\W*\w+){0,3})', 'gi');
var excerpts = regex.exec(content);
console.log(excerpts[0]);
返回' KEYWORD '而不是'包含KEYWORD且应该返回的内容'
我不知道发生了什么。我可能错过了一个符号/标志或者完全使用了错误的功能。在线正则表达式测试者我试过说正则表达式是合理的,但我无法得到正确的回报。救命啊!
答案 0 :(得分:3)
您需要转义反斜杠,因为您正在从new RegExp
构造创建正则表达式:
var content = 'This is my content which contains KEYWORD and should return seven words. ';
var regex = new RegExp('(?:(?:\\w+\\W*){0,3})' + 'keyword' + '(?:(?:\\W*\\w+){0,3})', 'gi');
var excerpts = regex.exec(content);
alert(excerpts[0]);
答案 1 :(得分:2)
(\\w+\\s){3}KEYWORD (\\w+\\s){2}\\w+