我有一个第一个文本文件,如下所示:12AB34.US。第二个文本文件是CD 34 EF。 我想在第一个文本文件中找到第二个文本文件是否存在。
我试图在第一个文本文件(.US)中最后切3个字符。然后,我拆分为每个2个字符(因为第二个文本文件包含2个字符)。然后,我尝试了此代码,并且始终返回“未找到”。
$String = Get-Content "C:\Users\te2.txt"
$Data = Get-Content "C:\Users\Fixed.txt"
$Split = $Data -split '(..)'
$Cut = $String.Substring(0,6)
$String_Split = $Cut -split '(..)'
$String_Split
$Check= $String_Split | %{$_ -match $Split}
if ($Check-contains $true) {
Write-Host "0"
} else {
Write-Host "1"
}
答案 0 :(得分:1)
您当前的方法存在很多问题。
# strings split into groups of two '12' 'AB' '34' # first string 'CD' ' 3' '4 ' # second string
使用-match
测试多个字符串时,您需要
.
)和$Compare = $FBString_Split | % {$Data_Split -match [regex]::Escape($_)}
if ($Compare -contains $true) {
Write-Host "Found"
} else {
Write-Host "Not Found"
}
要找到一种更通用的解决方案,以找出一个字符串的N个字符的任何个子字符串是否也是另一个字符串的子字符串,您可以改为执行以下操作:
$a = '12AB34.US'
$b = 'CD 34 EF'
# we want to test all substrings of length 2
$n = 2
$possibleSubstrings = 0..($n - 1) | ForEach-Object {
# grab substrings of length $n at every offset from 0 to $n
$a.Substring($_) -split "($('.'*$n))" | Where-Object Length -eq $n |ForEach-Object {
# escape the substring for later use with `-match`
[regex]::Escape($_)
}
} |Sort-Object -Unique
# We can construct a single regex pattern for all possible substrings:
$pattern = $possibleSubstrings -join '|'
# And finally we test if it matches
if($b -match $pattern){
Write-Host "Found!"
}
else {
Write-Host "Not found!"
}
这种方法将为您提供正确的答案,但是对于大输入量,它会变得非常慢,这时您可能需要查看基于非正则表达式的策略,例如Boyer-Moore