正则表达式中的$1和$2是什么?

14
在C#正则表达式中,$1和$2是指匹配模式中第一个和第二个捕获组的内容。它们都属于捕获组。

2
这些是.NET正则表达式语法的一部分。C#不支持正则表达式。所有正则表达式支持都是作为.NET Framework的一部分提供的。 - John Saunders
1
请提供您的正则表达式示例。$1、$2、$3在不同的上下文中可能意味着不同的事情。而@JohnSaunders是正确的。 - celerno
@celerno $1 是否可能是除了数字分组替换之外的其它东西? - David Heffernan
2个回答

21

这是按索引捕获组的值。$1是第一个捕获组,$2是第二个捕获组。正如David指出的那样,这些值用于替换模式。

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

输出:Hello World


4

这些是替换文本。具体来说是带编号的替换文本组。来自文档:

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

请问您能否解释一下以下链接中的示例?链接 第二个示例 string replacement = "$2"; - Viki888
这在我引用答案中的文档的第一段中有解释。$1是第一个捕获组,$2是第二个捕获组,以此类推。 - David Heffernan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接