本文介绍正则表达式在.NET中的基本应用,代码简单粗暴,实例浅显易懂,让你一分钟快速上手正则(大鸟请略过)。

本文为入门文章,很多时候我们只是忘记了语法,这也可作为一个快速查询的参考。 如果想深入学习正则表达式高级功能请参考其他资料

=========首先引入命名空间 using System.Text.RegularExpressions;

//1.查找
static void Test1()
{
Console.WriteLine("=========Match方法匹配第一个===========");
Regex regex = new Regex(@"\d{3}"); //@ 表示不用进行转义 \在.NET中是转义符 此表达式等同于 \\d{3}
Match m = regex.Match("this is an apple 123 456 9999");
Console.WriteLine(m); Console.WriteLine("=========Matches方法匹配所有===========");
MatchCollection matches = regex.Matches("this is an apple 123 456 9999");
foreach(Match match in matches)
{
Console.WriteLine(match);
} Console.WriteLine("=========IsMatch检查匹配是否成功===========");
bool result = regex.IsMatch("this is an apple 123 456 9999");
Console.WriteLine(result);
}

结果:=========

------------------------------------------------------------------------------------------------------------

//2.替换操作
static void Test2()
{
//替换所有匹配项
Regex regex = new Regex("apple");
string result = regex.Replace("this is an apple,apple,apple", "苹果");
Console.Write(result);
}

结果:=========

------------------------------------------------------------------------------------------------------------

 //3.使用委托
static void Test3()
{
string result = Regex.Replace("1 2 3 4 5",@"\d+", new MatchEvaluator(
delegate(Match match) {//匿名方法
return "" + match.Value;
}
),RegexOptions.IgnoreCase|RegexOptions.Singleline);
//最后一个参数匹配模式 可选
Console.WriteLine(result);
}

结果:=========

简单说明一下,Replace方法可以传入一个委托,对匹配结果自定义处理,new MatchEvaluator(delegate),delegate为方法名,Match作为参数传入, 这里使用了匿名方法。

------------------------------------------------------------------------------------------------------------

 //4.$number 使用表达式替换匹配结果中的 number 组  $1表示组1匹配的结果
static void Test4()
{
string result = Regex.Replace("1 2 3 12 13", @"(\d)(\d)", "A$1");
Console.WriteLine(result);
}

上面的正则表达式有两个分组 (\d) 和 (\d) 匹配结果如下图所示

Replace方法第三个参数 A$1 中的$1 表示使用 匹配结果中Group_1 的值 替换 字符串中所有匹配项 所以 A1替换 12 ,A1替换13 结果如下

如果参数换为 abc$2  表示使用匹配结果中 Group_2 的值 替换字符串中所有匹配项 所以 abc2替换 12 ,abc3替换13 结果如下

此处比较绕口,实在不明白请自行敲一下代码。

------------------------------------------------------------------------------------------------------------

//5.${name} 使用表达式替换匹配结果中的 name 组  ${name}表示组名为name匹配的结果 ?<name> 给改组命名为name
static void Test5() {
string result = Regex.Replace("1 2 3 12 13", @"(\d)(?<name>\d)", "A${name}");
Console.WriteLine(result); }
//补充
//$$ $转义符
//$& 替换整个匹配
//$^ 替换匹配前的字符
//$' 替换匹配后的字符
//$+ 替换最后匹配的组
//$_ 替换整个字符串
//(?#这个是注释) 正则内联注释语法 (?#注释)

给分组命名使用  ?<name> 如下图 命名以后Group_2 的组名为:name ,${name} 和上一节的$1类似 一个用编号引用 一个用名字引用

------------------------------------------------------------------------------------------------------------

//6.1分组
static void Test6()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(?<y>\d{4})-(?<m>\d{1,2})-(?<d>\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups["y"].Value);
int month = int.Parse(match.Groups["m"].Value);
int day = int.Parse(match.Groups["d"].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine(); //DateTime.Parse(s);
}

上面的代码可以用 DateTime.Parse(s) 实现,这里为了展示如何给分组命名和取值

=========

//6.2
static void Test7()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(\d{4})-(\d{1,2})-(\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups[].Value);
int month = int.Parse(match.Groups[].Value);
int day = int.Parse(match.Groups[].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine();
}

未命名的分组可以直接用编号取得 Groups[1],Groups[2],Groups[3]

=======

//6.3
static void Test8()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(?<2>\d{4})-(?<1>\d{1,2})-(?<3>\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups[].Value);
int month = int.Parse(match.Groups[].Value);
int day = int.Parse(match.Groups[].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine();
}

Groups[2] 这里的 2代表的是名字 而不是编号

===========================================================================

看到这里相信你对.NET中如何使用正则有了一个基本的认识, Regex类提供了很多静态的方法可以直接调用,很多时候可以不需要实例化。

//全部代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text.RegularExpressions;
namespace demo
{
class Program
{
static void Main(string[] args)
{
Test6(); Console.ReadLine();
} //1.查找
static void Test1()
{
Console.WriteLine("=========Match方法匹配第一个===========");
Regex regex = new Regex(@"\d{3}"); //@ 表示不用进行转义 \在.NET中是转义符 此表达式等同于 \\d{3}
Match m = regex.Match("this is an apple 123 456 9999");
Console.WriteLine(m); Console.WriteLine("=========Matches方法匹配所有===========");
MatchCollection matches = regex.Matches("this is an apple 123 456 9999");
foreach(Match match in matches)
{
Console.WriteLine(match);
} Console.WriteLine("=========Matches方法匹配所有===========");
bool result = regex.IsMatch("this is an apple 123 456 9999");
Console.WriteLine(result);
} //2.替换操作
static void Test2()
{
//替换所有匹配项
Regex regex = new Regex("apple");
string result = regex.Replace("this is an apple,apple,apple", "苹果");
Console.Write(result);
} //3.使用委托
static void Test3()
{
string result = Regex.Replace("1 2 3 4 5",@"\d+", new MatchEvaluator(
delegate(Match match) {//匿名方法
return "" + match.Value;
}
),RegexOptions.IgnoreCase|RegexOptions.Singleline);
//最后一个参数匹配模式 可选
Console.WriteLine(result);
} //4.$number 使用表达式替换匹配结果中的 number 组 $1表示组1匹配的结果
static void Test4()
{
string result = Regex.Replace("1 2 3 12 13", @"(\d)(\d)", "A$1");
Console.WriteLine(result);
} //5.${name} 使用表达式替换匹配结果中的 name 组 ${name}表示组名为name匹配的结果 ?<name> 给改组命名为name
static void Test5() {
string result = Regex.Replace("1 2 3 12 13", @"(\d)(?<name>\d)", "A${name}");
Console.WriteLine(result); }
//补充
//$$ $转义符
//$& 替换整个匹配
//$^ 替换匹配前的字符
//$' 替换匹配后的字符
//$+ 替换最后匹配的组
//$_ 替换整个字符串
//(?#这个是注释) 正则内联注释语法 (?#注释) //6.1分组
static void Test6()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(?<y>\d{4})-(?<m>\d{1,2})-(?<d>\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups["y"].Value);
int month = int.Parse(match.Groups["m"].Value);
int day = int.Parse(match.Groups["d"].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine(); //DateTime.Parse(s);
} //6.2
static void Test7()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(\d{4})-(\d{1,2})-(\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups[].Value);
int month = int.Parse(match.Groups[].Value);
int day = int.Parse(match.Groups[].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine();
} //6.3
static void Test8()
{
string s = "2005-2-21";
Regex reg = new Regex(@"(?<2>\d{4})-(?<1>\d{1,2})-(?<3>\d{1,2})", RegexOptions.Compiled);
Match match = reg.Match(s); int year = int.Parse(match.Groups[].Value);
int month = int.Parse(match.Groups[].Value);
int day = int.Parse(match.Groups[].Value); DateTime time = new DateTime(year, month, day);
Console.WriteLine(time);
Console.ReadLine();
} }
}

一分钟学会(一):.NET之正则表达式的更多相关文章

  1. 【译】10分钟学会Pandas

    十分钟学会Pandas 这是关于Pandas的简短介绍主要面向新用户.你可以参考Cookbook了解更复杂的使用方法 习惯上,我们这样导入: In [1]: import pandas as pd I ...

  2. 5分钟学会使用Less预编译器

    5分钟学会使用Less预编译器 Less是什么? LESS CSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法为CSS赋予了动态语言的特性,如变量.继承.运算.函数等,更方便 ...

  3. 【grunt第二弹】30分钟学会使用grunt打包前端代码(02)

    前言 上一篇博客,我们简单的介绍了grunt的使用,一些基础点没能覆盖,我们今天有必要看看一些基础知识 [grunt第一弹]30分钟学会使用grunt打包前端代码 配置任务/grunt.initCon ...

  4. 《量化投资:以MATLAB为工具》连载(2)基础篇-N分钟学会MATLAB(中)

    http://www.matlabsky.com/thread-43937-1-1.html   <量化投资:以MATLAB为工具>连载(3)基础篇-N分钟学会MATLAB(下)     ...

  5. 《量化投资:以MATLAB为工具》连载(1)基础篇-N分钟学会MATLAB(上)

    http://blog.sina.com.cn/s/blog_4cf8aad30102uylf.html <量化投资:以MATLAB为工具>连载(1)基础篇-N分钟学会MATLAB(上) ...

  6. [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例)

    [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例) 踏雁寻花 发表于 2015-8-23 23:31:28 https://www.itsk.com/thread-35 ...

  7. 50分钟学会Laravel 50个小技巧

    50分钟学会Laravel 50个小技巧 时间 2015-12-09 17:13:45  Yuansir-web菜鸟 原文  http://www.yuansir-web.com/2015/12/09 ...

  8. 10分钟学会Linux

    10分钟学会Linux有点夸张,可是能够让一个新手初步熟悉Linux中最重要最主要的知识,本文翻译的英文网页在众多Linux入门学习的资料中还是很不错的. 英文地址:http://freeengine ...

  9. PHP学习过程_Symfony_(3)_整理_十分钟学会Symfony

    这篇文章主要介绍了Symfony学习十分钟入门教程,详细介绍了Symfony的安装配置,项目初始化,建立Bundle,设计实体,添加约束,增删改查等基本操作技巧,需要的朋友可以参考下 (此文章已被多人 ...

  10. 30分钟学会使用Spring Web Services基础开发

    时隔一年终于又推出了一篇30分钟系列,上一篇<30分钟学会反向Ajax>是2016年7月的事情了.时光荏苒,岁月穿梭.虽然一直还在从事Java方面的开发工作,但是私下其实更喜欢使用C++. ...

随机推荐

  1. windows上传文件到linux

    1.在putty的网站上下载putty跟pscp 2.安装ssh跟putty sudo apt-get install openssh-server sudo apt-get install putt ...

  2. ASP 发送邮件

    ASP发送邮件源码 ASP通过调用API接口发送邮件 <% ' '网吧数据 'www.zgw8.com '邮件发送接口调用demo ' ' '获取网页源代码函数 '=============== ...

  3. How to push your code in git

    1. display all the branches git branch -a 2. delete branches git br -d <branch> # 删除某个分支 git b ...

  4. vi命令的使用

    <转:http://linux.vbird.org/linux_basic/0310vi.php> 基本上 vi 共分为三种模式,分别是『一般模式』.『编辑模式』与『指令列命令模式』. 圖 ...

  5. Citrix 服务器虚拟化之八 Xenserver虚拟机模版

    Citrix 服务器虚拟化之八 Xenserver虚拟机模版 XenServer与VMware不同,Vmware只能将现有的VM转换成模版,而XenServer具有两种方法:一种是将现有 VM 转换为 ...

  6. C++学习28 重载>>和<<(输入输出运算符)

    在C++中,系统已经对左移运算符“<<”和右移运算符“>>”分别进行了重载,使其能够用于输入输出,但是输入输出的处理对象只能是系统内建的数据类型.系统重载这两个运算符是以系统类 ...

  7. flexbox弹性盒模型

    div { display:flex; } div a{ }

  8. js注意事项

    在数组顶部插入一条数据 data.result.unshift({ Value: 'all', Text: '请选择分类' }); 执行iframe中的javascript方法 window.fram ...

  9. dwr demo教程

    中文版  http://ishare.iask.sina.com.cn/f/11908269.html 想找点资料,MB啊,操了,百度成屎了没啥好教程擦了,这些傻逼博主,写的Jb啥吗,代码不能跑,文字 ...

  10. HTTP 500 的解决方案

    我们首先要确定IIS权限的问题,如下所示: 身份验证的具体项: 身份验证的基本设置: 注意:如果不需要Form验证的情况下,那么把Form身份验证禁止掉,否则会出现在每一次请求的过程中都要有一个默认的 ...