首選的方法:
最簡單的方式準確地計算多子的出現大概是:
上的任何一個匹配
- 構建正則表達式模式子字符串
- 使用
-split
運算符分割字符串
- 計算字符串的結果數量和。減去1:
# Define the substrings and a sentence to test against
$Substrings = "a","an","the"
$Sentence = "a long long sentence to test the -split approach, anticipating false positives"
# Construct the regex pattern
# The \b sequence ensures "word boundaries" on either side of a
# match so that "a" wont match the a in "man" for example
$Pattern = "\b(?:{0})\b" -f ($Substrings -join '|')
# Split the string, count result and subtract 1
$Count = ($Sentence -split $Pattern).Count - 1
輸出:
C:\> $Count
2
正如你可以看到它已經匹配和拆分 「」 和 「」,而不是 「一個」 在上「期待」。
我會離開的運動轉換成該功能向讀者
注: 如果你開始喂不僅僅是簡單的ASCII字符串作爲輸入更多的,你可能需要之前逃離他們利用它們在模式:
$Pattern = "\b(?:{0})\b" -f (($Substrings |ForEach-Object {[regex]::Escape($_)}) -join '|')
原始的方法:
如果您對正則表達式感到不舒服,您可以假定兩個空格之間的任何內容都是「一個單詞」(就像在您的原始示例中一樣),然後遍歷句子中的單詞並檢查是否爲陣列包含問題的字(而不是其他方式):
$Substrings = "a","an","the"
$Sentence = (Read-Host "Enter a long sentence from a story book or novel: ").Split(" ")
$Counter = 0
foreach($Word in $Sentence){
if($Substrings -contains $Word){
$Counter++
}
}
由於suggested by Jeroen Mostert,你也可以利用哈希表。有了這個,你可以跟蹤每個單詞的出現,而不只是一個總數:
$Substrings = "a","an","the"
$Sentence = (Read-Host "Enter a long sentence from a story book or novel: ").Split(" ")
# Create hashtable from substrings
$Dictionary = @{}
$Substrings |ForEach-Object { $Dictionary[$_] = 0 }
foreach($Word in $Sentence){
if($Dictionary.ContainsKey($Word)){
$Dictionary[$Word]++
}
}
$Dictionary
'-contains'不工作的方式。你問的是拆分數組是否包含你指定的整個單詞數組,這顯然不是(它包含單詞,而不是數組)。你可以用循環來解決這個問題,或者通過將你的單詞列表存儲爲散列表並檢查其中的成員資格來更有效地解決問題。 –
感謝您的快速響應,所以您在說我應該將我的$ Array數組放入哈希表中? – SkullNerd