我试着匹配一个单词,它前面有空格,后面有空格,或者两者都有。
var sample = " test-abc -test# @test _test hello-test@ test test "就像在上述情况下,第一个‘测试’将计数,因为它有一个空间在它之前,下一个将不计数,因为它没有空间,第三个‘测试’将计算为它有一个空间之后,同样的第四个也将不计数,因为它没有空格前或后面,最后两个将像他们有空格前后。
function countOccurences(str,word){
var regex = new RegExp("(\\b|(?<=_))"+word+"(\\b|(?<=_))","gi");
console.log((str.match(regex)|| []).length);
}我所写的函数计算准确的单词,但不考虑空间,所以我得到的输出是7,但我想得到的是5。
发布于 2021-11-26 06:04:38
您可以在这里尝试使用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");
此处使用的regex模式表示匹配:
(?<=\s)test test preceded by whitespace
| OR
test(?=\s) test followed by whitespace请注意,这里的5场比赛是:
test-abc
@test
_test
test
testhttps://stackoverflow.com/questions/70120132
复制相似问题