Force immediate evaluation of backreference during replace

后端 未结 2 704
遥遥无期
遥遥无期 2020-12-12 02:00

I am running into an error where I am concatenating strings together to obtain the field I want replaced.

Below is an example of what my script is doing:



        
相关标签:
2条回答
  • 2020-12-12 03:01

    1st, missing the point, answer replaced...

    When concatenate '$1' and '6Q' (before being passed to the regex engine) you get $16Q and there is no 16th capture to replace.

    To avoid this, use named groups in the match ((?<name>)) and ${name} in the replacement string.

    See the documentation, and note:

    If number does not specify a valid capturing group defined in the regular expression pattern, $number is interpreted as a literal character sequence that is used to replace each match.

    0 讨论(0)
  • 2020-12-12 03:05

    You can also try using named capture groups:

    $rx = '(?i)(?<Beg>.*)\$\(STRINGTOREPLACE\)(?<End>.*)'
    $texttoreplacewith='${Beg}6Q${End}'
    $x = "abc`$(stringtoreplace)xyz"
    
    [regex]::Replace($x, $rx, $texttoreplacewith)
    
    0 讨论(0)
提交回复
热议问题