用正则表达式替换文档中的 HTML 不起作用

Replacing HTML in Document with Regex not working

我的脚本正在读入一个 HTML 文件,逐行扫描匹配的正则表达式以进行所需的更改。由于某种原因,当它到达第一个更改时,它不会进行更改,但通过测试它确实落入了 if 语句。

下面是应该更改的 PowerShell 脚本和文件部分。

$sig_regex = [regex]::Escape('241')
$sig_regex2 = [regex]::Escape('West')
$replace_1 = "PO"
$replace_2 = "Box 4816  Syracuse, New York  13221"
$new_html = @()

Get-Content $Path | foreach {
    $_

    #This is the section that should be replacing the line
    if ($_ -like $sig_regex) {
        $new_html += ($_ -replace $sig_regex, $replace_1)
    }

    #Replace content in line 2 of the address section (West)
    if ($_ -match $sig_regex2) {
        $new_html += ($_ -replace $sig_regex2, $replace_2)
    } else {
        #Stores any content that should not be changed into the new file
        $new_html += $_
    }
}

$new_html | Set-Content "C:\Newhtml.htm"

HTML:

<p class=MsoNormal style='line-height:150%;text-autospace:none'><span
style='font-size:9.0pt;line-height:150%;font-family:TeXGyreAdventor color:#002C5B'>241
West<o:p></o:p></span></p>

-Like 不是正则表达式运算符,而是 "wildcard" 运算符(想想 *?)。

您想改用 -Match

您可以试试这个...它使用 .net IO class。对于这么简单的事情,我也会忘记正则表达式。如果您正在寻找不时更改但仍遵循格式标准的内容,那么您应该使用正则表达式。

$sig_regex = '241'
$sig_regex2 = 'West'
$replace_1 = "PO"
$replace_2 = "Box 4816  Syracuse, New York  13221"
$new_html = @()

$file = [System.IO.File]::OpenText($Path)
while (!$file.EndOfStream) {
    $text = $file.ReadLine()
    if($text -match $sig_regex){
        $new_html += ($text -replace $sig_regex, $replace_1)
    }
    elseif ($text -match $sig_regex2) {
        $new_html += ($text -replace $sig_regex2, $replace_2)
    }
    else {
        $new_html += $text
    }
}

$new_html | Set-Content "C:\Newhtml.htm"