C # Use of the regular expression Regex class,
C # provides a very powerful function for the use of regular expressions, which is the Regex class. This package is included in the System. Text. RegularExpressions namespace. Basically, the DLL of this namespace does not need to be referenced separately in all project templates, and can be directly used.
1. Define a Regex class instance
Regex regex = new Regex (@ "\ d ");
The initialization parameter here is a regular expression, and "\ d" indicates configuring numbers.
2. Determine whether a match exists.
To determine whether a string matches a regular expression, you can use the Regex. IsMatch (string) method in the Regex object.
Regex. IsMatch ("abc"); // the return value is false. The string does not contain numbers.
Regex. IsMatch ("abc3abc"); // the return value is true because the string contains numbers.
3. Get matching times
Use the Regex. Matches (string) method to obtain a Matches set, and then use the Count attribute of the set.
Regex. Matches ("abc123abc"). Count;
The returned value is 3 because it matches three numbers.
4. Get matching content
Use the Regex. Match (string) method for matching.
Regex. Match ("abc123abc"). Value;
The return value is 1, indicating the first matched value.
5. Capture
In a regular expression, you can use parentheses to capture the partial score. To obtain the captured Value, you can use Regex. Match (string). Groups [int]. Value.
Regex regex = new Regex (@ "\ w (\ d *) \ w"); // match the number string between two letters
Regex. Match ("abc123abc"). Groups [0]. Value; // The returned Value is "123 ".
Using System; using System. text. regularExpressions; namespace Magci. test. strings {public class TestRegular {public static void WriteMatches (string str, MatchCollection matches) {Console. writeLine ("\ nString is:" + str); Console. writeLine ("No. of matches: "+ matches. count); foreach (Match nextMatch in matches) {// retrieves a matching string and a maximum of 10 peripheral characters int Index = nextMatch. index; string result = nextMatch. toStrin G (); int charsBefore = (Index <5 )? Index: 5; int fromEnd = str. Length-Index-result. Length; int charsAfter = (fromEnd <5 )? FromEnd: 5; int charsToDisplay = charsBefore + result. length + charsAfter; Console. writeLine ("Index: {0}, \ tString: {1}, \ t {2}", Index, result, str. substring (Index-charsBefore, charsToDisplay) ;}} public static void Main () {string Str = @ "My name is Magci, for short mgc. I like c sharp! "; // Search for" gc "string Pattern =" gc "; MatchCollection Matches = Regex. matches (Str, Pattern, RegexOptions. ignoreCase | RegexOptions. explicitCapture); WriteMatches (Str, Matches); // find the word Pattern = @ "\ bm \ S * c \ B" starting with "m" and ending with "c "; matches = Regex. matches (Str, Pattern, RegexOptions. ignoreCase | RegexOptions. explicitCapture); WriteMatches (Str, Matches );}}}