您的位置:首页 > 其它

正则表达式入门及备忘

2015-07-14 20:39 274 查看

概述

正则表达式,主要是用符号描述了一类特定的文本(模式)。而正则表达式引擎则负责在给定的字符串中,查找到这一特定的文本。

本文主要是列出常用的正则表达式符号,加以归类说明。本文仅仅是快速理解了正则表达式相关元字符,作一个备忘,供以后理解更复杂表达式的参考,以后关于正则表达式的相关内容会持续更新本文。示例语言用C#

概述

普通字符

字符集合

速记的字符集合

指定重复次数的字符

匹配位置字符

分支替换字符

匹配特殊字符

组,反向引用,非捕获组

贪婪与非贪婪

回溯与非回溯

正向预搜索、反向预搜索

最后

1 普通字符

最简单的一种文本描述,就是直接给出要匹配内容。 如要在”Generic specialization, the decorator pattern, chains of responsibilities, and extensible software.” 找到pattern,那么正则式就直接是”heels”即可

string input1 = "hello 1024 world 8080 bye";
Regex reg1 = new Regex(@"\d{4}(?= world)");
if (reg1.IsMatch(input1))
{
Console.WriteLine(reg1.Match(input1).Value);//output 1024
}

Regex reg2 = new Regex(@"\d{4}(?! world)");
if (reg2.IsMatch(input1))
{
Console.WriteLine(reg2.Match(input1).Value);//output 8080
}

Regex reg3 = new Regex(@"(?<=world )\d{4}");
if (reg3.IsMatch(input1))
{
Console.WriteLine(reg3.Match(input1).Value);//output 8080
}

Regex reg4 = new Regex(@"(?<!world )\d{4}");
if (reg4.IsMatch(input1))
{
Console.WriteLine(reg4.Match(input1).Value);//output 1024
}


View Code

最后

参考地址:

正则表达式30分钟入门教程

Regular Expressions Tutorial

NET Framework Regular Expressions

.NET进阶系列之一:C#正则表达式整理备忘
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: