C# - 正则表达式
一个正则表达式 是可以与输入文本匹配的模式。 .Net 框架提供了一个允许这种匹配的正则表达式引擎。模式由一个或多个字符文字、运算符或构造组成。
定义正则表达式的构造
有多种类别的字符、运算符和构造可让您定义正则表达式。单击以下链接可找到这些构造。
-
字符转义
-
字符类
-
锚
-
分组构造
-
量词
-
反向引用构造
-
交替构造
-
换人
-
杂项结构
正则表达式类
Regex 类用于表示正则表达式。它有以下常用方法 -
| Sr.No. | 方法和说明 |
|---|---|
| 1 | public bool IsMatch(字符串输入) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 2 | public bool IsMatch(string input, int startat) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中的指定起始位置开始。 |
| 3 | public static bool IsMatch(字符串输入,字符串模式) 指示指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
| 4 | 公共 MatchCollection 匹配(字符串输入) 在指定的输入字符串中搜索所有出现的正则表达式。 |
| 5 | 公共字符串替换(字符串输入,字符串替换) 在指定的输入字符串中,用指定的替换字符串替换所有匹配正则表达式模式的字符串。 |
| 6 | 公共字符串[] 拆分(字符串输入) 在 Regex 构造函数中指定的正则表达式模式定义的位置处将输入字符串拆分为子字符串数组。 |
有关方法和属性的完整列表,请阅读有关 C# 的 Microsoft 文档。
示例 1
以下示例匹配以“S”开头的单词 -
现场演示
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 = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
当上面的代码编译并执行时,它会产生以下结果 -
Matching words that start with 'S': The Expression: \bS\S* Splendid Suns
示例 2
以下示例匹配以 'm' 开头并以 'e' 结尾的单词 -
现场演示
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
示例 3
这个例子替换了额外的空白 -
现场演示
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
static void Main(string[] args) {
string input = "Hello World ";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
}
}
}
当上面的代码编译并执行时,它会产生以下结果 -
Original String: Hello World Replacement String: Hello World
C语言