这是按索引捕获组的值。$1是第一个捕获组,$2是第二个捕获组。正如David指出的那样,这些值用于替换模式。
string input = "Hello World";
string result = Regex.Replace(input, @"(\w+) (\w+)", "$2 $1");
输出:Hello World
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
$1
是第一个捕获组,$2
是第二个捕获组,以此类推。 - David Heffernan