How is regex used in C#?
In C#, Regex (regular expression) is a class used for handling string matching and replacement. It provides a powerful and flexible way to search, match, and manipulate text data.
Here are some common methods and uses of Regex:
- Check if the input string contains content that matches the pattern, and return a boolean value.
- Regex.Match(string input, string pattern): Search for the first string in the input string that matches the pattern and return a Match object containing the results.
- Regex.Matches(string input, string pattern): Searches the input string for all matches with the pattern, and returns a MatchCollection object that contains all the matching results.
- The Regex.Replace method searches for content within the input string that matches the specified pattern and replaces it with the specified replacement string.
- The method Regex.Split(string input, string pattern) is used to split the input string based on a specified pattern and return an array of strings.
- The special characters and syntax used in regular expressions, such as . (matches any character except for a newline), * (matches 0 or more times), + (matches 1 or more times), ? (matches 0 or 1 time), \d (matches a digit character), etc.
Original: 我希望你很快就好起来。
Paraphrased: I hope you recover quickly.
string input = "Hello, my name is John. I live in New York.";
string pattern = @"\b\w{4}\b"; // 匹配长度为4的单词
bool isMatch = Regex.IsMatch(input, pattern);
Match match = Regex.Match(input, pattern);
MatchCollection matches = Regex.Matches(input, pattern);
string replaced = Regex.Replace(input, pattern, "****");
string[] splitted = Regex.Split(input, @"\W+"); // 根据非单词字符进行分割
Console.WriteLine(isMatch); // 输出:True
Console.WriteLine(match.Value); // 输出:name
foreach (Match m in matches)
{
Console.WriteLine(m.Value); // 输出:name, John, live
}
Console.WriteLine(replaced); // 输出:Hello, my **** is ****. I **** in **** ****.
foreach (string s in splitted)
{
Console.WriteLine(s); // 输出:Hello, my, name, is, John, I, live, in, New, York
}
This is just one use case of the Regex class, there are many other functions and options available. Regex allows for more advanced and complex string matching and manipulation.