Note that PowerShell's -replace
operator is invariably global, i.e. it always looks for and replaces all matches of the given regex.
Use the following -replace
operation instead:
@'
111 is different from:
111 is different from:
123 is different from:
567.
'@ -replace '(?m)^(\d{3}) .+:(\r?\n)(?!\1)(?=(\d{3})\b)',
'$0 *** This value $3 ***$2'
Note: The @'<newline>...<newline>'@
string literal used for the multiline input text is a so-called here-string.
Output:
111 is different from:
111 is different from:
*** This value 123 ***
123 is different from:
*** This value 567 ***
567.
To spell out the fully dynamic substitution approach, adding 1
to the captured number in this example:
PowerShell (Core) 7+ solution, using a script block ({ ... }
) as -replace
's substitution operand:
@'
111 is different from:
111 is different from:
123 is different from:
567.
'@ -replace '(?m)^(\d{3}) .+:(\r?\n)(?!\1)(?=(\d{3})\b)', {
'{0} *** This value + 1: {1} ***{2}' -f $_.Value, ([int] $_.Groups[3].Value + 1), $_.Groups[2].Value
}
Windows PowerShell solution, where a direct call to the underlying
[regex]::Replace()
method is required:
$str = @'
111 is different from:
111 is different from:
123 is different from:
567.
'@
[regex]::Replace(
$str,
'(?m)^(\d{3}) .+:(\r?\n)(?!\1)(?=(\d{3})\b)',
{
param($m)
'{0} *** This value + 1: {1} ***{2}' -f $m.Value, ([int] $m.Groups[3].Value + 1), $m.Groups[2].Value
}
)
Output (note that 1
has been added to each captured value):
111 is different from:
111 is different from:
*** This value + 1: 124 ***
123 is different from:
*** This value + 1: 568 ***
567.