简体   繁体   English

正则表达式中的$ 1和$ 2是多少?

[英]What is $1 and $2 in Regular Expressions?

I have simple question regarding regular expressions in C#. 我对C#中的正则表达式有一个简单的问题。

What is $1 and $2 in C# regular expression? C#正则表达式的$ 1和$ 2是多少?

Does both come under groups? 两者都属于团体?

That is values of captured groups by index. 这是按索引捕获的组的值。 $1 is a first captured group, and $2 is a second captured group. $ 1是第一个被捕获的组,$ 2是第二个被捕获的组。 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 输出: World Hello

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. $ number语言元素包括替换字符串中数字捕获组匹配的最后一个子字符串,其中number是捕获组的索引。 For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. 例如,替换模式$ 1表示匹配的子字符串将由第一个捕获的组替换。 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. 使用(?)语法捕获未明确指定名称的组从左到右编号从1开始。 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. 例如,在正则表达式(\\ w)(?\\ d)中,名为group的数字的索引为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. 如果number未指定正则表达式模式中定义的有效捕获组,则$ number将被解释为用于替换每个匹配的文字字符序列。

The following example uses the $number substitution to strip the currency symbol from a decimal value. 以下示例使用$ number替换从十进制值中剥离货币符号。 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM