首页 > 解决方案 > Powershell 正则表达式的所有匹配问题和字符串之间的全部查找

问题描述

尝试使用 Powershell 去除某些但不是全部的 HTML 标记或其他代码。代码在文件中重复,所以我需要对 ALL 进行操作,而不仅仅是第一个。在 Powershell 中,我创建了一个包含我需要删除的所有项目的数组(用 '' 替换)和一个 FOR 循环来处理文件中的每个项目。这是我的代码(缩短以节省空间;完整列表大约有 20 项)和我需要删除的代码示例(出现在多行上)。

$THEREGEX = @(
 '<script (.*?)</script>',
 '<script>(.*?)</script>',
 '<style (.*?)</style>',
 '<style>(.*?)</style>'
)
for ($XX=0; $XX -lt $THEREGEX.count; $XX++)
{
 (Get-Content -path 2020allnav.html) -replace $THEREGEX[$XX],'' |
  Set-Content -path 2020allnav.html
} 

要删除的示例,请记住这在文件中重复。

<script>
<!--//--><![CDATA[//><!--
document.createElement( "picture" );
//--><!]]>
</script>

该脚本运行没有错误,但仍然无法工作。我认为我可能遇到的问题包括:没有对所有匹配项进行操作、不正确的 rexeg 语法、没有告诉脚本我这是正则表达式而不是字符串,以及可能还有其他我不知道的事情。抱歉,这是一个冗长而复杂的问题。

确实尝试在 Stackoverflow 中找到所有部分的答案,但我无法将它们拼凑在一起。谢谢。

标签: regexpowershell

解决方案


您想用“”替换所有模式,因此,您可以直接使用带有选项单行的正则表达式点网:(如果您想用“”替换所有模式,则不需要创建组模式)。

# form an array create an OR regex  a|b|c|d...
$THEREGEX = @(
 '<script (.*?)</script>', '<script>(.*?)</script>'
 '<style (.*?)</style>', '<style>(.*?)</style>'
) -join "|"

# load file
$html = Get-Content -Path 2020allnav.html -Encoding UTF8 -Raw

#replace all occurences, considering $text is not multiline but singleline
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline
$re = [regex]::new($THEREGEX, $option)
$newhtml = $re.Replace($html, "")

如果要保存字符串:

$newhtml |  Out-File x:\path\newfile.html -Encoding UTF8

推荐阅读