ljs.dev
ljs.dev

Reputation: 4493

Powershell replace regex between two tags

Given a block of arbitrary text enclosed by specific tags, I would like to replace the whole chunk with something else (in the example, "BANANA")

$newvar = $oldvar -replace "<!-- URL -->(*.)<!-- END -->","BANANA"

Is there a mode in PS regex to not require escaping and can the syntax then be as simple as this to achieve the replacement?

UPDATE: I understand now that it should be .*, not *., but still no dice. The match covers multiple lines, if that adds complexity to the regex or requires other options.

Upvotes: 1

Views: 2198

Answers (1)

zx81
zx81

Reputation: 41838

It looks to me like you have the .* in reverse (*.). Apart from that, try:

$newvar = $oldvar -creplace '(?s)<!-- URL -->.*?<!-- END -->', 'BANANA'
  • In response to your comments, I have made the .*? lazy so it will not "overmatch" (for details on lazy vs. greedy, see the reference section)
  • Also in reference to your comments, the (?s) activates DOTALL mode, allowing the .*? to match across multiple lines.

Reference

The Many Degrees of Regex Greed

Upvotes: 3

Related Questions