1

I want to replace the value in an XML using PowerShell. I have below string (a part of XML) want to replace 100 with different value

<stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>

I have tried below code which identify the required value but while replacing it replace all the numeric value

$DN = '<stringProp 79357name="ThreadGroup.79357num_threads">100</stringProp>'
$test =10000
[regex]$rx='^ThreadGroup.79357num_threads">(.+?)</stringProp>$'
$rx.Match($DN)
$DN = $rx.Replace($DN,'$1') -replace '\d+',$test
Write-Host $DN

After running above code I am getting below output

<stringProp 10000name="ThreadGroup.10000num_threads">10000</stringProp>

and am expecting

<stringProp name="ThreadGroup.10000num_threads">10000</stringProp>
0

1 Answer 1

2

Capturing groups are used in regex to extract part of a pattern match when we need to match those in specific contexts. Replacing captured texts is not directly supported, though with some coding it can be worked around.

Instead, use capturing groups to do what they are meant to do: capture what you need to keep and just match what you need to replace.

Use

$DN -replace '(ThreadGroup\.79357num_threads">).*?(</stringProp>)',"`${1}$test`$2"

The ThreadGroup.79357num_threads"> is captured with (ThreadGroup\.79357num_threads">) into Group 1 and </stringProp> is captured with (</stringProp>) into Group 2.

The "`${1}$test`$2" replacement is the contents of Group 1 ($1), then the value of the $test variable and then the value of Group 2. Note the backticks before $ are necessary for Powershell to treat them as literal $ chars, not the string extrapolating "marker".

You need ${1} and not $1 because the $test variable starts with a digit and when there is a digit straight after a backreference (like $1) the ID should be wrapped with curly braces to avoid ambiguity with the Group ID.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.