Owais Ahmed
Owais Ahmed

Reputation: 1438

Using replace in powershell script not replacing

Why replace is not working? Here is the code

$TestString = "<css>1</css><PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern><item>2</item>"
$NewString =  $TestString  -replace "<PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern>","<PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[0-9]+$</RegexPattern>"
write-host  $NewString

Is there something I am doing wrong?

Any suggestions would be appreciated.

Thanks in advance

Upvotes: 0

Views: 68

Answers (1)

Rob
Rob

Reputation: 648

The replace operator will replace a string matching a regex pattern. From the looks of it, you are attempting to replace a literal string with another literal string and both of them happen to also have a regex pattern in them. Use the Replace method instead

$TestString = "<css>1</css><PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern><item>2</item>"
$NewString =  $TestString.Replace("<PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[\da-zA-Z\s+()\-']+$</RegexPattern>","<PredefinedValidator>9DE32F03C2734FFCB2D681FF6283FE88</PredefinedValidator><RegexPattern>^[0-9]+$</RegexPattern>")
write-host  $NewString

Upvotes: 1

Related Questions