我有一个文件,有以下内容,我试图删除一切从<!--
到-->
<!--<br>
/* Font Definitions */
-->
Only keep this part
不要使用正则表达式。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
正则表达式再次拯救-
@'
<!--<br>
/* Font Definitions */
-->
Only keep this part
'@ -replace '(?s)<!--(.+?)-->', ''
(?s)
使点匹配新行:)