摆脱文件中不​​需要的html

时间:2014-08-14 02:44:48

标签: powershell

我有一个文件,其中包含以下内容,我正在尝试删除从<!---->

的所有内容
<!--<br>
/* Font Definitions */

-->
Only keep this part 

2 个答案:

答案 0 :(得分:1)

Don't use a regex. HTML不是常规语言,因此无法使用正则表达式对其进行正确解析。它大部分时间都会成功,但其他时候会失败。壮观。

我建议破解打开文件,并在时间读取一个字符,查找字符<!-,然后是-。然后,继续阅读,直到找到--!,然后是>

$chars = [IO.File]::ReadAllText( $path ).ToCharArray()
$newFileContent = New-Object 'Text.StringBuilder'
for( $i = 0; $i -lt $chars.Length; ++$i )
{
    if( $inComment )
    {
        if( $chars[$i] -eq '-' -and $chars[$i+1] -eq '-' -and $chars[$i+2] -eq '!' -and $chars[$i+3] -eq '>' )
        {
            $inComment = $false
            $i += 4
        }
        continue
    }

    if( $chars[$i] -eq '<' -and $chars[$i+1] -eq '!' -and $chars[$i+2] -eq '-' -and $chars[$i+3] -eq '-' )
    {
        $inComment = $true
        $i += 4
        continue
    }

    $newFileContent.Append( $chars[$i] )
}
$newFileContent.ToString() | Set-Content -Path $path

答案 1 :(得分:0)

再次救援的正则表达式 -

@'
<!--<br>
/* Font Definitions */

-->
Only keep this part 
'@ -replace '(?s)<!--(.+?)-->', ''

(?s)使点匹配新行:)