49. C# -- 正则表达式
C# 正则表达式
理论:
正则表达式 是一种匹配输入文本的模式。
.Net 框架提供了允许这种匹配的正则表达式引擎。
模式由一个或多个字符、运算符和结构组成。
定义正则表达式
下面列出了用于定义正则表达式的各种类别的字符、运算符和结构。
字符转义 字符类 定位点 分组构造 限定符 反向引用构造 备用构造 替换 杂项构造
字符转义 正则表达式中的反斜杠字符(\)指示其后跟的字符是特殊字符,或应按原义解释该字符.
定义正则表达式
下面列出了用于定义正则表达式的各种类别的字符、运算符和结构。
字符转义
字符类
定位点
分组构造
限定符
反向引用构造
备用构造
替换
杂项构造
字符转义
正则表达式中的反斜杠字符(\)指示其后跟的字符是特殊字符,或应按原义解释该字符。
下表列出了转义字符:
字符类
字符类与一组字符中的任何一个字符匹配。
下表列出了字符类:
分组构造
分组构造描述了正则表达式的子表达式,通常用于捕获输入字符串的子字符串。
下表列出了分组构造:
限定符
限定符指定在输入字符串中必须存在上一个元素(可以是字符、组或字符类)的多少个实例才能出现匹配项。 限定符包括下表中列出的语言元素。
下表列出了限定符:
替换
替换是替换模式中使用的正则表达式。
下表列出了用于替换的字符:
实例 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
参考:
http://outofmemory.cn/csharp/tutorial/csharp-regular-expressions.html
转载于:https://blog.51cto.com/57388/1656348