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语法不正确,没有告诉脚本我是regex而不是字符串,以及可能其他我不知道的事情。对不起,这是一个又长又复杂的问题。

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

您想用"quot;所以您可以直接使用带有选项singleline的regex dotnet:(如果您想用"替换所有,则不需要创建组家长(。

# 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:pathnewfile.html -Encoding UTF8

最新更新