我现在有一个foreach循环,它从一个小字典文件中获取内容(只有超过3个字符的字符串)。我希望将$line中的每个字符与我的其他字符进行比较,在这种情况下,"b“"i”"n“"g”"o“,这样如果$line中的所有字符都是宾果的,那么它就会打印单词。如果不是,它会循环到下一个单词。
到目前为止,我已经:
foreach($line in Get-Content Desktop/dict.txt | Sort-Object Length, { $_ })
我无法理解的地方(不太熟悉powershell)是:
if($line.length -gt 3){
if( i in $line == 'b')
if( i in $line == 'i')
if( i in $line == 'n')
if( i in $line == 'g')
if( i in $line == 'o')
write-output $line
}
}
发布于 2021-07-11 09:44:24
通过接受这两种答案的一部分,我得到了我想要的结果。由于我是新手,不知道该如何感谢马丁和圣地亚哥所做的工作。
这是放在一起的代码,它基本上接受了字典文件,而不是固定的字符串大小使其大于3:
$dict = @(Get-Content Desktop/dict.txt | Sort-Object Length, { $_ })
$word = 'bingo'
$dict |
Where-Object { $_.length -gt 2 } |
ForEach-Object {
$dictwordLetters = [System.Collections.Generic.List[char]]::new($_.ToCharArray())
$word.ToCharArray() | ForEach-Object {
$dictwordLetters.Remove($_) | Out-Null
}
if (-not $dictwordLetters.Count) {
$_
}
}
非常感谢你的协助。
发布于 2021-07-10 21:15:16
如果我正确理解,如果您想检查$line是否包含在宾果中,您可以使用-match表示不区分大小写,而-cmatch用于区分大小写的操作符。见比较算子。
例如:
PS /> 'bingo' -match 'ing'
True
PS /> 'bingo' -match 'bin'
True
PS /> 'bingo' -match 'ngo'
True代码可以如下所示:
foreach($line in Get-Content Desktop/dict.txt | Sort-Object Length, { $_ })
{
if($line.length -gt 3 -and 'bingo' -match $line)
{
$line
# you can add break here to stop this loop if the word is found
}
}编辑
如果要检查宾果中的3个或3个以上字符(按任何顺序排列)是否包含在$line中,有许多方法可以这样做,这是我将采取的方法:
# Insert magic word here
$magicWord = 'bingo'.ToCharArray() -join '|'
foreach($line in Get-Content Desktop/dict.txt | Sort-Object Length, { $_ })
{
# Remove [Text.RegularExpressions.RegexOptions]::IgnoreCase if you want it to be Case Sensitive
$check = [regex]::Matches($line,$magicWord,[Text.RegularExpressions.RegexOptions]::IgnoreCase)
# If 3 or more unique characters were matched
if(($check.Value | Select-Object -Unique).count -ge 3)
{
'Line is: {0} || Characters Matched: {1}' -f $line,-join $check.Value
}
}演示
鉴于以下几个字:
$test = 'ngob','ibgo','gn','foo','var','boing','ingob','oubingo','asdBINGasdO!'它将产生:
Line is: ngob || Characters Matched: ngob
Line is: ibgo || Characters Matched: ibgo
Line is: boing || Characters Matched: boing
Line is: ingob || Characters Matched: ingob
Line is: oubingo || Characters Matched: obingo
Line is: asdBINGasdO! || Characters Matched: BINGO发布于 2021-07-11 00:27:24
所以,你想要取回任何相同长度和相同字符的单词,不管顺序如何?
$dict = @(
'bingo'
'rambo'
'big'
'gobin'
'bee'
'ebe'
'been'
'ginbo'
)
$word = 'bingo'
$dict |
Where-Object { $_.length -eq $word.Length } |
ForEach-Object {
$dictwordLetters = [System.Collections.Generic.List[char]]::new($_.ToCharArray())
$word.ToCharArray() | ForEach-Object {
$dictwordLetters.Remove($_) | Out-Null
}
if (-not $dictwordLetters.Count) {
$_
}
}以下是输出
bingo
gobin
ginbohttps://stackoverflow.com/questions/68331254
复制相似问题