从变量中获取匹配的字数

Get matched word count from a variable

我想得到 $channel 变量中 test 个单词的总数,但是 $a returns 与 $channel 相同。

$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test" 

这里的确切解决方案应该是什么?

使用 -AllMatches 参数开关获取来自 Select-String 的所有匹配项:

$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test" -AllMatches

$a 将包含一个 MatchInfo 对象。数一数其Matches

$a.Matches.Count
$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
([regex]::Matches($channel, "test" )).count

会给你匹配的计数:7