用Regex替换Document中的HTML不起作用

时间:2018-03-08 13:21:27

标签: html regex powershell powershell-v4.0

我的脚本正在读取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>

2 个答案:

答案 0 :(得分:1)

-Like不是正则表达式运算符,而是“通配符”运算符(想想*?)。

您想改用-Match

答案 1 :(得分:0)

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

$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"