什么是C#中的Regex类及其类方法?
Regex类用于表示正则表达式。正则表达式是可以与输入文本匹配的模式。
以下是Regex类的方法-
指示在Regex构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。
指示在Regex构造函数中指定的正则表达式是否从字符串的指定起始位置开始在指定的输入字符串中找到匹配项。
指示指定的正则表达式是否在指定的输入字符串中找到匹配项。
在指定的输入字符串中搜索所有出现的正则表达式。
在指定的输入字符串中,用指定的替换字符串替换与正则表达式模式匹配的所有字符串。
在Regex构造函数中指定的正则表达式模式所定义的位置,将输入字符串拆分为子字符串数组。
以下示例使用该Matches()方法搜索指定的输入字符串-
示例
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}
}输出结果
Matching words start with 'm' and ends with 'e': The Expression: \bm\S*e\b make maze manage measure