regular expression matches more than it should

Cliff 21 Reputation points

Hi I have a script that tries to replace one a block of <p></p> with text image002.jpg or png. but it always replace more that it should. Could someone help to improve the regex. I did ask ChatGPT but no luck:=). The one who got the answer must smarter than AI.

# 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

<p class=xmsonormal style="background:white">to be kept 2</p>

$pattern = "(?s)<p\b[^>]*>.*?\bimage002\.(png|jpg)\b.*?</p>"
$replacement = "<p>replaced</p>"

[regex]::Replace($content, $pattern, $replacement, [System.Text.RegularExpressions.RegexOptions]::Singleline)
# Use -replace operator to find and replace all matches
$content = $content -replace $pattern,$replacement
# Write the modified content to the console or a file
Write-Host $content

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,007 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 29,311 Reputation points Microsoft Vendor


    Please see if this meets your needs.


    Best Regards,

    Ian Xue

    If the Answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful