C# 中的正则表达式是什么
csharpprogrammingserver side programming更新于 2025/10/15 18:37:17
正则表达式是一种可以与输入文本匹配的模式。.NET 框架提供了一个允许此类匹配的正则表达式引擎。一个模式由一个或多个字符文字、运算符或构造函数组成。
例如,如果要匹配以"S"开头的单词,请使用 C# 中的正则表达式,如以下代码所示 −
示例
using System;
using System.Text.RegularExpressions;
namespace Demo {
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 = "Email Sent Today!";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
输出
Matching words that start with 'S': The Expression: \bS\S* Sent
C# 中用于正则表达式的 Regex 类具有以下方法:
| Sr.No | 方法 &说明 |
|---|---|
| 1 | public bool IsMatch(string input) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 2 | public bool IsMatch(string input, int start) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中指定的起始位置开始。 |
| 3 | public static bool IsMatch(string input, string pattern) 指示指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 4 | public MatchCollection Matches(string input) 在指定的输入字符串中搜索所有出现的正则表达式。 |
| 5 | public string Replace(string input, string replacement) 在指定的输入字符串中,用指定的替换字符串替换所有与正则表达式模式匹配的字符串。 |
| 6 | public string[] Split(string input) 将输入字符串拆分为子字符串数组,拆分位置由 Regex 构造函数中指定的正则表达式模式定义。 |

