Regex replacement capture followed by digit

前端 未结 1 413
無奈伤痛
無奈伤痛 2020-12-03 17:09

I am trying to get a Regex replacement working to update my AssemblyInfo.cs files, so I have:

Regex.Replace(
    contents, 
    @\"(\\[assembly: Assembly(Fil         


        
相关标签:
1条回答
  • Use ${1} instead of $1. This is also the substitution syntax for named capturing group (?<name>).

    Here's a snippet to illustrate (see also on ideone.com):

    Console.WriteLine(Regex.Replace("abc", "(.)", "$11"));        // $11$11$11
    Console.WriteLine(Regex.Replace("abc", "(.)", "${1}1"));      // a1b1c1
    Console.WriteLine(Regex.Replace("abc", "(?<x>.)", "${x}1"));  // a1b1c1
    

    This behavior is explicitly documented:

    Regular Expression Language Elements - Substitutions

    Substituting a Numbered Group

    The $number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group.

    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.

    Substituting a Named Group

    The ${name} language element substitutes the last substring matched by the name capturing group, where name is the name of a capturing group defined by the (?<name>) language element.

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

    0 讨论(0)
提交回复
热议问题