SoFunction
Updated on 2025-03-01

A brief tutorial on using Regex class for C#

C# provides a very powerful function for the use of regular expressions, which is the Regex class. This package is included in the namespace, and the DLL where this namespace is located basically does not need to add references separately in all project templates, and can be used directly.

1. Define an instance of the Regex class

Copy the codeThe code is as follows:
Regex regex = new Regex(@"\d");

The initialization parameter here is a regular expression, "\d" means the configuration number.

2. Determine whether it matches

To determine whether a string matches a regular expression, you can use the (string) method in the Regex object.

Copy the codeThe code is as follows:

("abc"); //The return value is false, and the string does not contain a number
("abc3abc"); //The return value is true because the string contains the number

3. Get the number of matches

Use the (string) method to get a Matches collection, and then use the Count property of this collection.

Copy the codeThe code is as follows:

("abc123abc").Count;

The return value is 3 because the number is matched three times.

4. Get matching content

Use the (string) method to match.

Copy the codeThe code is as follows:

("abc123abc").Value;

The return value is 1, indicating the first matching value.

5. Capture

In regular expressions, some values ​​can be captured using brackets. To obtain the captured value, you can use string.Groups[int].Value to obtain it.

Copy the codeThe code is as follows:

Regex regex = new Regex(@"\w(\d*)\w"); //Match the string of numbers between two letters
("abc123abc").Groups[0].Value; //The return value is "123".

Regarding C# calling Regex class to use regular expressions, Brother Hong has roughly introduced so much, and he will add it later when encountering other situations.