簡體   English   中英

如何使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM