regex - 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 中找到所有部分的答案,但我无法将它们拼凑在一起。谢谢。
解决方案
您想用“”替换所有模式,因此,您可以直接使用带有选项单行的正则表达式点网:(如果您想用“”替换所有模式,则不需要创建组模式)。
# 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
推荐阅读
- javascript - Javascript 日期格式自定义
- python - 类继承和实例化 - 对 __init__() 和 __new__() 方法的内部调用之间的混淆
- reactjs - 如何有条件地渲染使用钩子的 React 组件
- c++ - C++ 编译错误:错误:“尝试”之前的预期主表达式
- ssh - 使用 java jcabi SSH 客户端(或其他)在 shell 中执行多个命令
- kdb - 在 KDB 中使用的 Q 语言
- javascript - 如何使用 CustomJS 更新 Bokeh 源
- python-3.x - 仅使用 numpy 和 itertools 加载文本文件段
- .net - 无法绕过或忽略 IIS/.NET 中的默认错误页面
- r - 在 R 中绘制一个向量作为另一个向量的函数