What is $1 and $2 in Regular Expressions?

后端 未结 2 1838
北荒
北荒 2021-01-02 00:10

I have simple question regarding regular expressions in C#.

What is $1 and $2 in C# regular expression?

Does both come under groups?

相关标签:
2条回答
  • 2021-01-02 00:58

    These are substitutions. Specifically numbered group substitutions. From the documentation:

    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. For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs in Regular Expressions.

    Capturing groups that are not explicitly assigned names using the (?) syntax are numbered from left to right starting at one. Named groups are also numbered from left to right, starting at one greater than the index of the last unnamed group. For example, in the regular expression (\w)(?\d), the index of the digit named group is 2.

    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.

    The following example uses the $number substitution to strip the currency symbol from a decimal value. It removes currency symbols found at the beginning or end of a monetary value, and recognizes the two most common decimal separators ("." and ",").

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = @"\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*";
          string replacement = "$1";
          string input = "$16.32 12.19 £16.29 €18.29  €18,29";
          string result = Regex.Replace(input, pattern, replacement);
          Console.WriteLine(result);
       }
    }
    // The example displays the following output: 
    //       16.32 12.19 16.29 18.29  18,29
    
    0 讨论(0)
  • 2021-01-02 01:09

    That is values of captured groups by index. $1 is a first captured group, and $2 is a second captured group. As David pointed, these values used in replacement patterns.

    string input = "Hello World";
    string result = Regex.Replace(input, @"(\w+) (\w+)", "$2 $1");
    

    Output: World Hello

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