查找跨越文本的多行并使用PowerShell替换

MrG*_*ant 4 regex powershell

我正在使用正则表达式搜索来匹配和替换一些文本.文本可以跨越多行(可能有也可能没有换行符).目前我有这个:

 $regex = "\<\?php eval.*?\>"

Get-ChildItem -exclude *.bak | Where-Object {$_.Attributes -ne "Directory"} |ForEach-Object {
 $text = [string]::Join("`n", (Get-Content $_))
 $text -replace $RegEx ,"REPLACED"}
Run Code Online (Sandbox Code Playgroud)

ste*_*tej 5

试试这个:

$regex = New-Object Text.RegularExpressions.Regex "\<\?php eval.*?\>", ('singleline', 'multiline')

Get-ChildItem -exclude *.bak |
  Where-Object {!$_.PsIsContainer} |
  ForEach-Object {
     $text = (Get-Content $_.FullName) -join "`n"
     $regex.Replace($text, "REPLACED")
  }
Run Code Online (Sandbox Code Playgroud)

通过New-Object显式创建正则表达式,以便可以传入选项.

  • 我认为你想要`Where-Object {!$ _. PSIsContainer}`并且它绝对是一种更好的IMO方式(与测试属性相比). (2认同)