我有一个第一个文本文件,如下所示:12AB34.US。第二个文本文件是CD 34 EF。我想在第一个文本文件中找到我的第二个文本文件。
我试图在第一个文本文件(.US)中最后剪切3个字符。然后我分成每2个字符(因为第2个文本文件由2个字符组成)。然后,我尝试了这个代码,它总是返回“Not Found”。
$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"
}
您当前的方法存在许多问题。
# 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这样的非正则表达式策略