![](/img/trans.png)
[英]Regular expression for check if string has two specified words javascript
[英]How can i match a word in a string which has two same words before it using JavaScript regular expression?
例如:“ foo foo bar word ”,它将与单词“ bar ”匹配,因为“ bar ”前面有两个相同的单词“ foo ”。 似乎javascript正则表达式不支持零宽度正向后看方法。 因此,如何找到替代方法来解决此问题。
这是一个简单的可能的解决方案。
//get an array of words.
var words = string.split(' ');
//loop through the words
for(var i = 2; i < words.length; i++){
//lets skip the first 2 words.
if(words[i-1] === words[i-2]){
//the last 2 words are equal.
//your match is here.
}
}
您还可以跟踪lastWord变量,并对照它进行检查,以减少数组查找。 但是我认为这通常被认为比正则表达式更容易阅读,但在内存方面则不那么容易。
您可以使用正则表达式向后引用并使用regex.exec()获得结果。
describe('back reference', () => {
it('matching with regex.exec()', () => {
let source = `foo foo bar word ooh ooh ooh yes`;
let regex = /(\w+)(?:\W+\1)+\W+(\w+)/g;
expect(regex.exec(source)[2]).toEqual('bar');
expect(regex.exec(source)[2]).toEqual('yes');
expect(regex.exec(source)).toBeNull();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.