在 Powershell 中使用正则表达式的单词计数器

word counter with regex in powershell

var words = "word worddd woord wooord 45555";

var wordCount = words.match(/([a-zA-Z]\w+)/g).length;

if(wordCount == 4 || wordCount == 6 ){
  WScript.Echo(wordCount);//Result 4
}

如何制作一个像 jscript

一样工作的 ps1 脚本

一般来说:Measure-Object cmdlet 有一个 -Word 开关:

$words = "word worddd woord wooord"

$wordCount = ($words | Measure-Object -Word).Words

if ($wordCount -in 4, 6){
   $wordCount # -> 4
}

注意:如果您确实需要 PS v2 支持,请使用 4, 6 -contains $wordCount 代替 $wordCount -in 4, 6


要将被视为单词的内容限制为以(ASCII 范围)字母 开头的内容,如您的问题所示,需要做更多的工作:

$words = "word worddd woord wooord 45555"

# Count only words that start with an (ASCII-range) letter.
$wordCount = ((-split $words) -match '^[a-z]\w+$').Count

if ($wordCount -in 4, 6){
   $wordCount # -> 4, because '45555' wasn't counted.
}
  • -split的一元形式,即string splitting operator,通过空格将字符串拆分为一个标记数组。

  • -matchregular-expression matching operator,再次将每个结果标记与 RHS 正则表达式匹配:

    • -match 默认查找 substrings,因此需要锚点 ^$
    • -match 默认情况下 不区分大小写 (PowerShell 通常如此),因此 [a-z] 涵盖小写和大写字母。
  • (...).Count returns 匹配标记的结果数组的长度(元素计数)。