【问题标题】:Multiline Regex in PowerShellPowerShell 中的多行正则表达式
【发布时间】:2014-03-21 14:26:42
【问题描述】:

我有这个 PowerShell 脚本,其主要目的是在文件夹中搜索 HTML 文件,找到特定的 HTML 标记,然后用我告诉它的内容替换。

我已经完成了 3/4 的查找和替换工作。我遇到的问题涉及正则表达式。

这是我试图让我的正则表达式查找和替换的标记:

<a href="programsactivities_skating.html"><br />
                                           </a>

这是我目前拥有的正则表达式,以及我在其中使用它的函数:

automate -school "C:\Users\$env:username\Desktop\schools\$question" -query '(?mis)(?!exclude1|exclude2|exclude3)(<a[^>]*?>(\s|&nbsp;|<br\s?/?>)*</a>)' -replace ''

这里是自动化功能:

function automate($school, $query, $replace) {
    $processFiles = Get-ChildItem -Exclude *.bak -Include "*.html", "*.HTML", "*.htm", "*.HTM" -Recurse -Path $school
    foreach ($file in  $processFiles) {
        $text = Get-Content $file
        $text = $text -replace $query, $replace
        $text | Out-File $file -Force -Encoding utf8
    }
}

我已经尝试找出解决这个问题的方法大约 2 天了,但似乎无法让它发挥作用。我已经确定问题是我需要告诉我的正则表达式来解释多行,这就是我遇到的问题。

非常感谢任何人提供的任何帮助。

提前致谢。

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    Get-Content 生成一个字符串数组,其中每个字符串包含输入文件中的一行,因此您将无法匹配超过一行的文本段落。如果您希望能够匹配多行,则需要将数组合并为一个字符串:

    $text = Get-Content $file | Out-String
    

    [String]$text = Get-Content $file
    

    $text = [IO.File]::ReadAllText($file)
    

    请注意,1st 和 2nd 方法不会保留输入文件中的换行符。正如 Keith 在 cmets 中指出的那样,方法 2 只是简单地破坏所有换行符,方法 1 在加入数组时将 &lt;CR&gt;&lt;LF&gt; 放在每行的末尾。在处理 Linux/Unix 或 Mac 文件时,后者可能是个问题。

    【讨论】:

    • 或者,如果您使用的是 V3 或更高版本 $text = Get-Content $file -raw。顺便说一句,最后一个例子要小心,因为它不保留换行符。
    【解决方案2】:

    我不明白你想用那些排除元素做什么,但我发现多行正则表达式通常更容易在此处字符串中构造:

    $text = @'
    <a href="programsactivities_skating.html"><br />
                                           </a>
    '@
    
    $regex = @'
    (?mis)<a href="programsactivities_skating.html"><br />
    \s+?</a>
    '@
    
    $text -match $regex
    
    True
    

    【讨论】:

      【解决方案3】:

      Get-Content 将返回一个字符串数组,您想连接有问题的字符串以创建一个:

      function automate($school, $query, $replace) {
          $processFiles = Get-ChildItem -Exclude *.bak -Include "*.html", "*.HTML", "*.htm", "*.HTM" -Recurse -Path $school
          foreach ($file in  $processFiles) {
              $text = ""
              $text = Get-Content $file | % { $text += $_ +"`r`n" }
              $text = $text -replace $query, $replace
              $text | Out-File $file -Force -Encoding utf8
          }
      }
      

      【讨论】:

      • 为什么不 $text = (Get-Content $file) -join "`r`n" 或者如上所述:$Text = Get-Content $file |外串
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多