You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 = 
@'
&lt;p class=xmsonormal style=&quot;background:white&quot;&gt;to be kept 1&lt;/p&gt;

&lt;p class=xmsonormal style=&quot;background:white&quot;&gt;&lt;span style=&quot;font-family:&quot;Source Sans Pro&quot;,sans-serif;
color:black&quot;&gt;&lt;!--[if gte vml 1]&gt;&lt;v:shape id=&quot;Picture_x0020_2&quot; o:spid=&quot;_x0000_i1028&quot;
 type=&quot;#_x0000_t75&quot; alt=&quot;&quot; style=&quot;width:75pt;height:75pt&quot;&gt;
 &lt;v:imagedata src=&quot;test_files/image002.png&quot; o:href=&quot;cid:98eba38d-7414-46ec-a87a-8eca235a6e5c&quot;/&gt;
&lt;/v:shape&gt;&lt;![endif]--&gt;&lt;![if !vml]&gt;&lt;img border=0 width=100 height=100
src=&quot;test_files/image002.png&quot; style=&quot;height:1.041in;width:1.041in&quot; v:shapes=&quot;Picture_x0020_2&quot;&gt;&lt;![endif]&gt;&lt;/span&gt;&lt;span
style=&quot;color:black&quot;&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p class=xmsonormal style=&quot;background:white&quot;&gt;to be kept 2&lt;/p&gt;
'@

# 优化后的正则模式
$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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:37:08