1
votes

Using REGEX (in PowerShell) I would like to find a pattern in a text file that is over two lines and replace it with new text and preserve the whitespace. Example text:

    ObjectType=Page
    ObjectID=70000

My match string is

RunObjectType=Page;\s+RunObjectID=70000

The result I want is

   ObjectType=Page
   ObjectID=88888

The problem is my replacement string

RunObjectType=Page;`n+RunObjectID=88888

returns

       ObjectType=Page
ObjectID=88888

And I need it to keep the original spacing. To complicate matters the amount of spacing may change.

Suggestions?

1

1 Answers

1
votes

Leverage a capturing group and a backreference to that group in the replacement pattern:

$s -replace 'RunObjectType=Page;(\s+)RunObjectID=70000', 'RunObjectType=Page;$1RunObjectID=88888'

See the regex demo

With the (\s+), you capture all the whitespaces into the Group 1 buffer and then, using $1 backreference, the value is inserted into the result.

enter image description here