例子是:
$testLines = "050 BLACK Michael Douglas 32 Kellogs Court Wondertown Fitter","056 WHITE Brian Dennis 101 Wood Street Wondertown Court Worker"
# hash table for linking a street type to the street name using an underscore
$streetTypeHash = @{
' Drive ' = '_Drive, ';
' Street ' = '_Street, ';
' Court Worker ' = ' Court Worker '; # include any term that may be mistakenly referenced. Ensure it remains unchanged.
' Court ' = '_Court, ';
}
# read the street type (e.g Street, Road, Drive, Court etc) & join with underscore to street name
for ($i = 0; $i -lt $testLines.Count; $i ) {
foreach ($Key in $streetTypeHash.Keys) {
if ($testLines[$i] -match $Key) {
$testLines[$i] = $testLines[$i] -replace $Key, $($streetTypeHash[$Key])
}
}
$testLines[$i]
輸出的第二行顯示了問題:
050 BLACK Michael Douglas 32 Kellogs_Court, Wondertown Fitter
056 WHITE Brian Dennis 101 Wood_Street, Wondertown_Court, Worker
我的理解是:第一個可用的匹配是“Court”。無論是否有任何其他字符是密鑰字串的一部分。因此,不可能使用這種方法來否定錯誤匹配。我嘗試使用另一個哈希表:
$notStreetTypeHash = @{
' Court Worker ' = ' Court Worker ';
}
但是使用這兩個哈希表中的相應鍵來查找-match&-notMatch不起作用。
任何建議表示贊賞。
uj5u.com熱心網友回復:
如果我理解正確,您可以將整個程序簡化為:
$testLines = @(
"050 BLACK Michael Douglas 32 Kellogs Court Wondertown Fitter"
"056 WHITE Brian Dennis 101 Wood Street Wondertown Court Worker"
)
$testLines -replace '\s(Drive|Street|Court)\s(?!Worker)', '_$1, '
有關詳細資訊,請參閱https://regex101.com/r/6S10JI/1。
uj5u.com熱心網友回復:
到目前為止,我可以告訴你,你實際上在哪里使用字典來做你想做的事情。然而,正如@Santiago在他的有用答案中指出的那樣,-matchor-replace運算子的鍵應該更多地采用正則運算式格式。
因為 eg' Drive '可以更好地被單詞邊界包圍而不是空格(因為這也將包括例如行尾):'\bDrive\b'.
正如您自己發現的那樣,您不能在密鑰中包含例外,因為這里的一般設計用作OR運算子:如果模式匹配DriveOR StreetORCourt然后替換它。這意味著您的例外需要成為相關正則運算式的一部分:if DriveOR StreetOR ( CourtAND not Court Worker) then ...。您可以使用例如前瞻正則運算式來做到這一點:
$streetTypeHash = @{
'\bDrive\b' = '_Drive, '
'\bStreet\b' = '_Street, '
'\bCourt\s (?!Worker)\b' = '_Court, ' # Court, but not Court Worker
}
foreach ($Line in $testLines) {
$streetTypeHash.Keys |ForEach-Object {
$Line = $Line -Replace $_, $streetTypeHash[$_]\
}
$Line
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517251.html
標籤:电源外壳哈希表匹配
