0

I have a problem about regular expressions. I wonder is it possible to evaluate a math expression on the matched result of a regular expression in powershell? I can't use powershell to evaluate it, only must regex.

Problem Statement:

I have a code something like following:

$id = $reader.GetValue(0).ToString();
$col1 = $reader.GetValue(1).ToString();
$col2 = $reader.GetValue(2).ToString();
$col3 = $reader.GetValue(3).ToString();
$col4 = $reader.GetValue(4).ToString();
$col5 = $reader.GetValue(5).ToString();
$col6 = $reader.GetValue(6).ToString();
$col7 = $reader.GetValue(7).ToString();
...

I need to increase by 3 indexes 0, 1, 2, etc. in GetValue() text with Find & Replace dialog of Powershell ISE.

Result should be like that:

$id = $reader.GetValue(3).ToString();
$col1 = $reader.GetValue(4).ToString();
$col2 = $reader.GetValue(5).ToString();
$col3 = $reader.GetValue(6).ToString();
$col4 = $reader.GetValue(7).ToString();
$col5 = $reader.GetValue(8).ToString();
$col6 = $reader.GetValue(9).ToString();
$col7 = $reader.GetValue(10).ToString();
...

I was try

Find what: GetValue\((\d)\)
Replace with: GetValue($1+3)

But I couldn't success, and I couldn't find any document or reasonable solution about the problem.

Very thanks in advance for any possible solution.

1 Answers1

1

You can use

PS> $s = '$col1 = $reader.GetValue(1).ToString();'
PS> $rx = [regex]'(?<=GetValue\()\d+(?=\))'
PS> $rx.Replace($s, { param($m) [int]$m.Value + 1 })
$col1 = $reader.GetValue(2).ToString();

Details:

  • The regex pattern is compiled as a regex object here
  • The pattern is re-written to only consume one or more digits, the rest is wrapped with non-consuming lookarounds (a (?<=GetValue\() is a positive lookbehind and (?=\)) is a positive lookahead) so that further match manipulation could be simpler
  • The Regex.Replace method with match evaluator is used, and the { param($m) [int]$m.Value + 1 } part takes the match value (what \d+ matches), casts the string to integer value, adds 1 and the result is put back instead of the digits consumed.

See the regex demo. Details:

  • (?<=GetValue\() - immediately to the left of the current location, there must be GetValue( text
  • \d+ - one or more digits
  • (?=\)) - immediately to the right of the current location, there must be a ) char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563