用于计算特定事件的正则表达式模式

Regex pattern to count a certain occurrences

我正在尝试匹配前面或后面或两者都有 space 的单词。

var sample = " test-abc -test# @test _test hello-test@ test test "

就像上面的例子一样,第一个 'test' 会被计算在内,因为它前面有一个 space,下一个不会被计算,因为它没有 space,第三个 'test' 会算作它后面有一个 space,类似地,第四个也是,第五个不会算作前面或后面没有 space,最后两个会像它们一样前后 space 秒。

function countOccurences(str,word){
       var regex = new RegExp("(\b|(?<=_))"+word+"(\b|(?<=_))","gi");
       console.log((str.match(regex)|| []).length);
    }

我写的函数计算了确切的单词但没有考虑 space 所以我得到的输出是 7 但我想要得到的是 5.

您可以在此处尝试使用 match()

var sample = " test-abc -test# @test _test hello-test@ test test ";
var matches = sample.match(/(?<=\s)test|test(?=\s)/g, sample);
console.log("There were " + matches.length + " matches of test with whitespace on one side");

此处使用的正则表达式匹配:

(?<=\s)test  test preceded by whitespace
|            OR
test(?=\s)   test followed by whitespace

请注意,此处的 5 场比赛是:

test-abc
@test
_test
test
test