PowerShell正则表达式匹配范围超出预期,求优化方案
解决PowerShell正则替换误删无关
元素的问题
你的正则表达式因启用单行模式后匹配范围失控,导致跨多个<p>元素匹配,误删了包含“to be kept”的元素。核心问题是原正则中的.*?在单行模式下会匹配换行符,从而跨越不同的<p>块。
优化后的正则方案
修改正则表达式,确保匹配范围严格限定在单个<p>元素内部:
$pattern = "(?s)<p\b[^>]*>(?:(?!</p>).)*?\bimage002\.(png|jpg)\b(?:(?!</p>).)*?</p>"
正则规则说明
(?:(?!</p>).)*?:使用负向前瞻断言,匹配任意字符但不会越过</p>标签,彻底避免跨<p>元素匹配。<p\b[^>]*>:精准匹配带属性的<p>起始标签。- 保留对
image002.png/image002.jpg的精准匹配,确保只替换包含目标图片的<p>块。
修改后的完整脚本
# Assign the input text to a variable using single quotes $content = @' <p class=xmsonormal style="background:white">to be kept 1</p> <p class=xmsonormal style="background:white"><span style="font-family:"Source Sans Pro",sans-serif; color:black"><!--[if gte vml 1]><v:shape id="Picture_x0020_2" o:spid="_x0000_i1028" type="#_x0000_t75" alt="" style="width:75pt;height:75pt"> <v:imagedata src="test_files/image002.png" o:href="cid:98eba38d-7414-46ec-a87a-8eca235a6e5c"/> </v:shape><![endif]--><![if !vml]><img border=0 width=100 height=100 src="test_files/image002.png" style="height:1.041in;width:1.041in" v:shapes="Picture_x0020_2"><![endif]></span><span style="color:black"><o:p></o:p></span></p> <p class=xmsonormal style="background:white">to be kept 2</p> '@ # 优化后的正则模式 $pattern = "(?s)<p\b[^>]*>(?:(?!</p>).)*?\bimage002\.(png|jpg)\b(?:(?!</p>).)*?</p>" $replacement = "<p>replaced</p>" # 执行替换并输出结果 $content = $content -replace $pattern, $replacement Write-Host $content
效果验证
运行脚本后,仅包含image002.png的<p>元素会被替换为<p>replaced</p>,两个带有“to be kept”文本的<p>元素将完整保留。
内容的提问来源于stack exchange,提问作者Cliff
相关产品推荐
相关产品推荐

