What is $ 1 and $ 2 in regular expressions?

I have a simple question regarding regular expressions in C #.

What is $ 1 and $ 2 in C # regex?

Are both groups suitable?

+7
c # regex
source share
2 answers

These are the values ​​of captured groups by index. $ 1 is the first captured group, and the second is the second captured group. As David pointed out, these values ​​are used in replacement patterns.

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

Exit: World Hello

+9
source share

This is a lookup . In particular, numbered permutations of groups . From the documentation:

The $ number language element includes the last substring corresponding to the number capture group in the replacement string, where number is the index of the capture group. For example, a replacement pattern of $ 1 indicates that the matched substring should be replaced by the first captured group. For more information about numbering capture groups, see grouping constructs in regular expressions.

Capture groups that do not have explicitly assigned names using (?) Numbered from left to right, starting with one. Named groups are also numbered from left to right, starting with one larger than the index of the last unnamed group. For example, in the regular expression (\ w) (? \ D), the discharge category index is 2.

If the number does not indicate a valid capture group defined in the regular expression pattern, $ number is interpreted as a literal character sequence, which is used to replace each match.

The following example uses the replacement $ number so that the currency symbol is from a decimal value. It removes the currency symbols found at the beginning or end of the 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 
+3
source share

All Articles