我对可能很简单的事情有困难。本质上,我想返回数组中字符的任何实例,我的示例应该比这个解释更清晰。需要注意的一件事是,我将在循环中执行此操作,并且索引不会相同,所讨论的字母也不会相同,因此据我所知,我无法使用 .indexof 或子字符串;
$array = "asdfsdgfdshghfdsf"
$array -match "d"
返回:真
我希望它返回:ddd
有点像 bash 中的 grep
我对可能很简单的事情有困难。本质上,我想返回数组中字符的任何实例,我的示例应该比这个解释更清晰。需要注意的一件事是,我将在循环中执行此操作,并且索引不会相同,所讨论的字母也不会相同,因此据我所知,我无法使用 .indexof 或子字符串;
$array = "asdfsdgfdshghfdsf"
$array -match "d"
返回:真
我希望它返回:ddd
有点像 bash 中的 grep
您可以使用运算符-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
使用 select-string -allmatches,匹配对象数组将包含所有匹配项。-join 将匹配项转换为字符串。
$array = 'asdfsdgfdshghfdsf'
-join ($array | select-string d -AllMatches | % matches)
dddd