String truncation of C # -- Regex. Match,
The first two blogs, string truncation of C #-Substring and string truncation of C #-Split, respectively introduced the Substring function and Split function, you can also extract the Organization Name, instructor name, course type, and course name from "institution name/instructor name/course type/Course name. Today, I will introduce how to use regular expressions to implement this function.
Regex. Match method:Search for the substring that matches the Regular Expression Pattern in the input string, and return the first Match as a single Match object.
There are six types of Regex. Match methods that can be reloaded. The following describes how to use the Regex. Match method to implement the functions we need:
Public Match (string input): searches for the first matching item of the regular expression specified in the Regex constructor in the specified input string. Parameter: string of the matching item to be searched; returned result: a Match object containing matching information.
Match object: indicates the matching result of a single regular expression. The Groups attribute of the Match object is: Get the set of Groups matched by regular expressions.
If you want to use the Regex. Match method, first add using System. Text. RegularExpressions; reference.
Static void Main (string [] args) {string s1 = "institution name/instructor name/course type/Course name "; // define a regular expression Regex regex = new Regex (@"(. *)/(. *)/(. *)/(. *) ", RegexOptions. ignoreCase); // display each sub-string that meets the regular expression foreach (var I in regex. match (s1 ). groups) {Console. writeLine (I );}}
The Regex. Match method also implements the string truncation function we want, but the construction of regular expressions is a weakness compared with the previous Substring and Split functions. However, as long as we spend a little time studying it, the regular expression is not that hard to understand...
The string truncation function can be summarized as much as it is now. There may be other better methods. Let's take a look at it later ......