我有一个正则表达式,当我使用各种在线正则表达式测试网站时返回正确的结果。但是,当我在PowerShell脚本中使用正则表达式时,它只返回一行而不是多行。我希望这里的PowerShell专家可以告诉我我做错了什么。我使用的是PowerShell v1。
这是我的正则表达式: https://regex101.com/r/eA5jB2/3
这是我的powershell脚本: -
#Read the file
$FilePath = "testfile.txt"
$regex = '(?msi)^0[12][VM](?:[^\n]|\n(?!0[12][VM]|50|90))+'
get-content $FilePath | select-string -pattern $regex
返回是一行
01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 01 01
而不是
01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 01 01
01=0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01=5xxxxxxxxxxxxxxxxxxxxxxxxxxx
答案 0 :(得分:1)
问题出在Get-Content
cmdlet中,因为它返回一个行数组,因此您无法匹配文本除以换行符。
尝试使用其他方法获取文件内容:
[IO.File]::ReadAllText($FilePath)
Get-Content $FilePath -Raw
Get-Content $FilePath | Out-String
您可以找到类似的问题here。
答案 1 :(得分:0)
我认为问题在于使用Select-String。
$text =
@'
00 date
01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01 01 01 01=0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01=5xxxxxxxxxxxxxxxxxxxxxxxxxxx
01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01 01 01 01=0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01=9xxxxxxxxxxxxxxxxxxxxxxxxxxx
50 xxxxxxxxxxxxx xxxxxxxxxxxxxxxxx
01Vxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01$1 xxxxxxxxxxxxxxxxx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