我對可能很簡單的事情有困難。基本上我想回傳陣列中字符的任何實體,我這里的示例應該比這個解釋更清晰。需要注意的一件事是,我將在回圈中執行此操作,并且索引不會相同,所討論的字母也不會相同,因此據我所知,我不能使用 .indexof 或子字串;
$array = "asdfsdgfdshghfdsf"
$array -match "d"
回傳: 真
我希望它回傳什么:ddd
像 bash 中的 grep 一樣
uj5u.com熱心網友回復:
您可以使用-replace運營商洗掉任何東西,不是一個d:
PS ~> $string = "asdfsdgfdshghfdsf"
PS ~> $string -replace '[^d]'
dddd
需要注意的是在PowerShell中的所有字串運算子是大小寫在默認情況下,使用敏感的-creplace區分大小寫的更換:
PS ~> $string = "abcdABCD"
PS ~> $string -replace '[^d]'
dD
PS ~> $string -creplace '[^d]'
d
您可以從這樣的字串生成負字符類模式:
# define a string with all the characters
$allowedCharacters = 'abc'
# generate a regex pattern of the form `[^<char1><char2><char3>...]`
$pattern = '[^{0}]' -f $allowedCharacters.ToCharArray().ForEach({[regex]::Escape("$_")})
然后像以前一樣使用 with -replace(or -creplace) :
PS ~> 'abcdefgabcdefg' -replace $pattern
abcabc
uj5u.com熱心網友回復:
使用 select-string -allmatches,matches 物件陣列將包含所有匹配項。-join 將匹配項轉換為字串。
$array = 'asdfsdgfdshghfdsf'
-join ($array | select-string d -AllMatches | % matches)
dddd
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331899.html
