正则表达式
发布时间:2020-12-14 06:20:06 所属栏目:百科 来源:网络整理
导读:正则表达式是一种可以和输入文本相匹配的表达式。.Net framework 提供了一个正则表达式引擎让这种匹配成为可能。一个表达式可以由一个或多个字符,运算符,或结构体组成。 构建正则表达式的定义 有很多种类的字符,运算符,结构体可以定义正则表达式。 转义
正则表达式是一种可以和输入文本相匹配的表达式。.Net framework 提供了一个正则表达式引擎让这种匹配成为可能。一个表达式可以由一个或多个字符,运算符,或结构体组成。 构建正则表达式的定义有很多种类的字符,运算符,结构体可以定义正则表达式。
Regex 正则表达式类Regex 类用于表示一个正则表达式。它有下列常用的方法:
有关属性和方法的完成列表,请参见微软的 C# 文档。 示例 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,@"bSS*"); Console.ReadKey(); } } } 编译执行上述代码,得到如下结果: Matching words that start with 'S': The Expression: bSS* Splendid Suns 示例 2下面的例子中找出了以 m 开头以 e 结尾的单词 using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string 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,@"bmS*eb"); Console.ReadKey(); } } } 编译执行上述代码,得到如下结果: Matching words start with 'm' and ends with 'e': The Expression: bmS*eb 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- objective-c – 尝试在表格边界之外创建UITableView的table
- 忘记思科交换机密码处理步骤
- xml:Invalid byte 2 of 2-byte UTF-8 sequence
- cocos2dx 3.0遇到的问题解决记录
- iphone – 如何将值传递给父视图控制器?
- Test Driven Development (TDD)介绍
- c# – 计数或跳过(1).Any()我想要找出是否有超过1条记录 –
- centos6安装GitLab全程详解和常见问题解决
- 在c / c中为有限差分法创建五对角稀疏矩阵的最佳方法是什么
- Binary XML file line #13: Duplicate id 0x7f070055, tag