Regex用法详解.doc_第1页
Regex用法详解.doc_第2页
Regex用法详解.doc_第3页
Regex用法详解.doc_第4页
Regex用法详解.doc_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Regex用法详解 using System;using System.Text.RegularExpressions;namespace MetarCommonSupport/ / 通过Framwork类库中的Regex类实现了一些特殊功能数据检查/ public class MetarnetRegex private static MetarnetRegex instance = null; public static MetarnetRegex GetInstance() if(MetarnetRegex.instance = null) MetarnetRegex.instance = new MetarnetRegex(); return MetarnetRegex.instance; private MetarnetRegex() / / 判断输入的字符串只包含汉字 / / / public static bool IsChineseCh(string input) Regex regex = new Regex(u4e00-u9fa5+$); return regex.IsMatch(input); / / 匹配3位或4位区号的电话号码,其中区号可以用小括号括起来, / 也可以不用,区号与本地号间可以用连字号或空格间隔, / 也可以没有间隔 / (0d2)- ?d8|0d2- ?d8|(0d3)- ?d7|0d3- ?d7 / / / public static bool IsPhone(string input) string pattern = (0d2)- ?d8$|0d2- ?d8$|(0d3)- ?d7$|0d3- ?d7$; Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 判断输入的字符串是否是一个合法的手机号 / / / public static bool IsMobilePhone(string input) Regex regex = new Regex(13d9$); return regex.IsMatch(input); / / 判断输入的字符串只包含数字 / 可以匹配整数和浮点数 / -?d+$|(-?d+)(.d+)?$ / / / public static bool IsNumber(string input) string pattern = -?d+$|(-?d+)(.d+)?$; Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 匹配非负整数 / / / / public static bool IsNotNagtive(string input) Regex regex = new Regex(d+$); return regex.IsMatch(input); / / 匹配正整数 / / / public static bool IsUint(string input) Regex regex = new Regex(0-9*1-90-9*$); return regex.IsMatch(input); / / 判断输入的字符串字包含英文字母 / / / public static bool IsEnglisCh(string input) Regex regex = new Regex(A-Za-z+$); return regex.IsMatch(input); / / 判断输入的字符串是否是一个合法的Email地址 / / / public static bool IsEmail(string input) string pattern = (w-.+)(0-91,3.0-91,3.0-91,3.)|(w-+.)+)(a-zA-Z2,4|0-91,3)(?)$; Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 判断输入的字符串是否只包含数字和英文字母 / / / public static bool IsNumAndEnCh(string input) string pattern = A-Za-z0-9+$; Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 判断输入的字符串是否是一个超链接 / / / public static bool IsURL(string input) /string pattern = http:/(w-+.)+w-+(/w- ./?%&=*)?; string pattern = a-zA-Z+:/(w+(-w+)*)(.(w+(-w+)*)*(?S*)?$; Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 判断输入的字符串是否是表示一个IP地址 / / 被比较的字符串 / 是IP地址则为True public static bool IsIPv4(string input) string IPs = input.Split(.); Regex regex = new Regex(d+$); for(int i = 0; i 255) return false; return true; / / 计算字符串的字符长度,一个汉字字符将被计算为两个字符 / / 需要计算的字符串 / 返回字符串的长度 public static int GetCount(string input) return Regex.Replace(input,u4e00-u9fa5/g,aa).Length; / / 调用Regex中IsMatch函数实现一般的正则表达式匹配 / / 要匹配的正则表达式模式。 / 要搜索匹配项的字符串 / 如果正则表达式找到匹配项,则为 true;否则,为 false。 public static bool IsMatch(string pattern, string input) Regex regex = new Regex(pattern); return regex.IsMatch(input); / / 从输入字符串中的第一个字符开始,用替换字符串替换指定的正则表达式模式的所有匹配项。 / / 模式字符串 / 输入字符串 / 用于替换的字符串 / 返回被替换后的结果 public static string Replace(string pattern, string input, string replacement) Regex regex = new Regex(pattern); return regex.Replace(input,replacement); / / 在由正则表达式模式定义的位置拆分输入字符串。 / / 模式字符串 / 输入字符串 / public static string Split(string pattern, string input) Regex regex = new Regex(pattern); return regex.Split(input); / / 判断输入的字符串是否是合法的IPV6 地址 / / / public static bool IsIPV6(string input) string pattern = ; string temp = input; string strs = temp.Split(:); if(strs.Length 8) return false; int count = MetarnetRegex.GetStringCount(input,:); if(count1) return false; else if(count = 0) pattern = (da-f1,4:)7da-f1,4$; Regex regex = new Regex(pattern); return regex.IsMatch(input); else pattern = (da-f1,4:)0,5:(da-f1,4:)0,5da-f1,4$; Regex regex1 = new Regex(pattern); return regex1.IsMatch(input); /* * * 1、通过“:”来分割字符串看得到的字符串数组长度是否小于等于8 * 2、判断输入的IPV6字符串中是否有“:”。 * 3、如果没有“:”采用 (da-f1,4:)7da-f1,4$ 来判断 * 4、如果有“:” ,判断:是否止出现一次 * 5、如果出现一次以上 返回false * 6、(da-f1,4:)0,5:(da-f1,4:)0,5da-f1,4$ * */ / / 判断字符串compare 在 input字符串中出现的次数 / / 源字符串 / 用于比较的字符串 / 字符串compare 在 input字符串中出现的次数 private static int GetStringCount(string input, string compare) int index = input.IndexOf(compare); if(index != -1) return 1 + GetStringCount(input.Substring(index + compare.Length),compare); else return 0; /zh-cn/library/system.text.regularexpressions.regex.aspxRegex 类.NET Framework 4 其他版本 .NET Framework 3.5 .NET Framework 3.0 .NET Framework 2.0 Silverlight 此内容为质量更高的人工翻译。若想同时查看此页面和原始英文页面的内容,请单击“首选项”然后选择“经典视图”作为您的查看首选项。表示不可变的正则表达式。 命名空间: System.Text.RegularExpressions程序集: System(在 System.dll 中) 语法 VB C# C+ F# JScript 复制 声明 _Public Class Regex _Implements ISerializable备注 Regex 类表示 .NET Framework 的正则表达式引擎。 它可用来快速分析大量的文本,以查找特定字符模式;提取、编辑、替换或删除文本子字符串;或将提取的字符串添加到集合中,以便生成报告。 说明 如果您的主要兴趣是通过确定是否符合特定模式来验证字符串,则可以使用 System.Configuration.RegexStringValidator 类。 若要使用正则表达式,请使用正则表达式语言元素中记录的语法,定义要在文本流中识别的模式。 接下来,您可以选择实例化 Regex 对象。 最后,执行某种操作,如替换与正则表达式模式匹配的文本或标识模式匹配。 Regex vs。字符串方法System.String 类包括多种搜索和比较方法,可用于执行模式与文本的匹配。 例如,String.Contains、String.EndsWith 和 String.StartsWith 方法确定字符串实例是否包含指定的子字符串;String.IndexOf、String.IndexOfAny、String.LastIndexOf 和 String.LastIndexOfAny 方法返回字符串中指定的子字符串的起始位置。 搜索特定字符串时,使用 System.String 类的方法。 搜索字符串中的特定模式时,使用 Regex 类。 有关更多信息和示例,请参见.NET Framework 正则表达式。 静态与实例方法定义正则表达式模式之后,可以使用以下两种方式之一将其提供给正则表达式引擎。 实例化表示正则表达式的 Regex 对象。 若要执行此操作,应将正则表达式模式传递给 Regex 构造函数。 Regex 对象是不可变的;当您使用正则表达式实例化 Regex 对象时,将无法更改该对象的正则表达式。 向 static(在 Visual Basic 中为 Shared)Regex 方法同时提供正则表达式和要搜索的文本。 这使您无需显式创建 Regex 对象即可使用正则表达式。 所有 Regex 模式标识方法均同时包括静态重载和实例重载。 正则表达式引擎必须编译特定的模式,然后才可以使用该模式。 因为 Regex 对象不可变,这是调用 Regex 类构造函数或静态方法时发生的一次性过程。 为了避免重复编译单个正则表达式,正则表达式引擎将缓存在静态方法调用中所使用的已编译正则表达式。 因此,正则表达式模式匹配方法为静态方法和实例方法提供了同等的性能。 重要事项 在 .NET Framework 版本 1.0 和 1.1 中,所有已编译的正则表达式都会被缓存,而不论它们是在实例中使用还是静态方法调用。 从 .NET Framework 2.0 开始,只有静态方法调用中使用的正则表达式才会被缓存。 但是,由正则表达式引擎实现的缓存系统在以下两种情况下可能对性能产生不利影响: 当使用大量的正则表达式进行静态方法调用时。 默认情况下,正则表达式引擎将缓存 15 个最近使用的静态正则表达式。 如果应用程序使用的静态正则表达式超过 15 个,则必须重新编译某些正则表达式。 为了防止执行此类重新编译,您可以将 Regex.CacheSize 属性增加到适当的值。 当应用程序使用先前已编译的正则表达式实例化新的 Regex 对象时。 例如,下面的代码定义一个正则表达式,以定位某个文本流的各个行中重复的单词。 虽然本示例使用一个正则表达式,但它将实例化一个新的 Regex 对象来处理每行文本。 这将导致在每次循环迭代时都重新编译此正则表达式。 VB C# C+ F# JScript 复制 Dim sr As New StreamReader(filename)Dim input As StringDim pattern As String = b(w+)s1bDo While sr.Peek() = 0 input = sr.ReadLine() Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase) Dim matches As MatchCollection = rgx.Matches(input) If matches.Count 0 Then Console.WriteLine(0 (1 matches):, input, matches.Count) For Each match As Match In matches Console.WriteLine( + match.Value) Next End IfLoopsr.Close() 若要防止重新编译,此应用程序应实例化一个 Regex 对象,该对象供需要它的所有代码访问,如以下重写示例所示。 VB C# C+ F# JScript 复制 Dim sr As New StreamReader(filename)Dim input As StringDim pattern As String = b(w+)s1bDim rgx As New Regex(pattern, RegexOptions.IgnoreCase)Do While sr.Peek() = 0 input = sr.ReadLine() Dim matches As MatchCollection = rgx.Matches(input) If matches.Count 0 Then Console.WriteLine(0 (1 matches):, input, matches.Count) For Each match As Match In matches Console.WriteLine( + match.Value) Next End IfLoopsr.Close() 执行正则表达式操作无论您决定是实例化一个 Regex 对象并调用其方法,还是调用静态方法,Regex 类都将提供以下模式匹配功能: 验证匹配。 您可以调用 IsMatch 方法以确定是否存在匹配。 检索单个匹配。 您可以调用 Match 方法来检索 Match 对象,该对象表示字符串或字符串一部分中的第一个匹配项。 后续匹配项可以通过调用 Match.NextMatch 方法进行检索。 检索所有匹配。 您可以调用 Matches 方法来检索 System.Text.RegularExpressions.MatchCollection 对象,该对象表示在字符串或字符串一部分中找到的所有匹配项。 替换匹配的文本。 您可以调用 Replace 方法来替换匹配的文本。 此替换文本还可通过正则表达式来定义。 此外,某些 Replace 方法包括一个 MatchEvaluator 参数,该参数使您能够以编程方式定义替换文本。 创建字符串数组,该数组是由输入字符串的各个部分构成。 您可以调用 Split 方法,在正则表达式定义的位置拆分输入字符串。 除了其匹配模式方法之外,Regex 类还包括几种特殊用途的方法: Escape 方法可以对任何在正则表达式或输入字符串中可能被解释为正则表达式运算符的字符进行转义。 Unescape 方法移除这些转义字符。 CompileToAssembly 方法创建一个包含预定义正则表达式的程序集。 .NET Framework 在 System.Web.RegularExpressions 命名空间中包含这些特殊用途的程序集的示例。 示例 下面的示例使用正则表达式检查字符串中重复出现的词。 正则表达式 b(?w+)s+(k)b 可按下表中的方式解释。 模式 Description b 从单词边界开始匹配。 (?w+) 匹配一个或多个单词字符(最多可到单词边界)。 将此捕获组命名为 word。 s+ 匹配一个或多个空白字符。 (k) 匹配名为 word 的捕获组。 b 与字边界匹配。 VB C# C+ F# JScript 复制 Imports SystemImports System.Text.RegularExpressionsPublic Module Test Public Sub Main() Define a regular expression for repeated words. Dim rx As New Regex(b(?w+)s+(k)b, _ RegexOptions.Compiled Or RegexOptions.IgnoreCase) Define a test string. Dim text As String = The the quick brown fox fox jumped over the lazy dog dog. Find matches. Dim matches As MatchCollection = rx.Matches(text) Report the number of matches found. Console.WriteLine(0 matches found in:, matches.Count) Console.WriteLine( 0, text) Report on each match. For Each match As Match In matches Dim groups As GroupCollection = match.Groups Console.WriteLine(0 repeated at positions 1 and 2, _ groups.Item(word).Value, _ groups.Item(0).Index, _ groups.Item(1).Index) Next End SubEnd Module The example produces the following output to the console: 3 matches found in: The the quick brown fox fox jumped over the lazy dog dog. The repeated at positions 0 and 4 fox repeated at positions 20 and 25 dog repeated at positions 50 and 54下面的示例演示如何使用正则表达式来检查字符串是表示货币值还是具有表示货币值的正确格式。 在这种情况下,将从用户的当前区域性的 NumberFormatInfo.CurrencyDecimalSeparator、CurrencyDecimalDigits、NumberFormatInfo.CurrencySymbol、NumberFormatInfo.NegativeSign 和 NumberFormatInfo.PositiveSign 属性中动态生成正则表达式。 如果系统的当前区域性为 en-US,导致的正则表达式将是 w*+-? w? $? w?(d*.? d2?)1$. 此正则表达式可按下表中所示进行解释。 模式 Description 在字符串的开头处开始。 w* 匹配零个或多个空白字符。 +-? 匹配正号或负号的零个或一个匹配项。 w? 匹配零个或一个空白字符。 $? 匹配美元符号的零个或一个匹配项。 w? 匹配零个或一个空白字符。 d* 匹配零个或多个十进制数字。 .? 匹配零个或一个小数点符号。 d2? 匹配两位十进制数零次或一次。 (d*.?d2?)1 至少匹配一次由小数点符号分隔整数和小数的模式。 $ 匹配字符串的末尾部分。 在这种情况下,正则表达式假定有效货币字符串不包括组分隔符,并且此字符串既没有小数数字,也没有由当前区域性的 CurrencyDecimalDigits 属性定义的小数位数。 VB C# C+ F# JScript 复制 Imports System.GlobalizationImports System.Text.RegularExpressionsPublic Module Example Public Sub Main() Get the current NumberFormatInfo object to build the regular expression pattern dynamically. Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo Define the regular expression pattern. Dim pattern As String pattern = w* Get the positive and negative sign symbols. pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + ?w? Get the currency symbol. pattern += Regex.Escape(nfi.CurrencySymbol) + ?w? Add integral digits to the pattern. pattern += (d* Add the decimal separator. pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + ? Add the fractional digits. pattern += d Determine the number of fractional digits in currency values. pattern += nfi.CurrencyDecimalDigits.ToString() + ?)1$ Dim rgx As New Regex(pattern) Define some test strings. Dim tests() As String = -42, 19.99, 0.001, 100 USD, _ .34, 0.34, 1,052.21, $10.62, _ +1.43, -$0.23 Check each test string against the regular expression. For Each test As String In tests If rgx.IsMatch(test) Then Console.WriteLine(0 is a currency value., test) Else Console.WriteLine(0 is not a currency value., test) End If Next End SubEnd Module The example displays the following output: -42 is a currency value. 19.99 is a currency value. 0.001 is not a currency value. 100 USD is not a currency value. .34 is a currency value. 0.34 is a currency value. 1,052.21 is not a currency value. $10.62 is a currency value. +1.43 is a currency value. -$0.23 is a currency value.因为本示例中的正则表达式是动态生成的,所以在设计时我们不知道正则表达式引擎是否可能将当前区域性的货币符号、小数符号或正号及负号错误解释为正则表达式语言运算符。 若要防止任何解释错误,本示例将每个动态生成的字符串传递到 Escape 方法。 继承层次结构 System.Object System.Text.RegularExpressions.RegexSystem.Web.RegularExpressions.AspCodeRegexSystem.Web.RegularExpressions.AspEncodedExprRegexSystem.Web.RegularExpressions.AspExprRegexSystem.Web.RegularExpressions.CommentRegexSystem.Web.RegularExpressions.DatabindExprRegexSystem.Web.RegularExpressions.DataBindRegexSystem.Web.RegularExpressions.DirectiveRegexSystem.Web.RegularExpressions.EndTagRegexSystem.Web.RegularExpressions.GTRegexSystem.Web.RegularExpressions.IncludeRegexSystem.Web.RegularExpressions.LTRegexSystem.Web.RegularExpressions.RunatServerRegexSystem.Web.RegularExpressions.ServerTagsRegexSystem.Web.RegularExpressions.SimpleDirectiveRegexSystem.Web.RegularExpressions.TagRegexSystem.Web.RegularExpressions.TagRegex35System.Web.RegularExpressions.TextRegex线程安全 Regex 类本身是线程安全和不可变的(只读的)。 可以在任何线程上创建 Regex 对象,并在线程间共享。 有关更多信息,请参见线程安全。 平台 Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, WindowsMillennium Edition, Windows 98, Xbox 360, Zune.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。 版本信息 .NET Framework受以下版本支持:4、3.5、3.0、2.0、1.1、1.0.NET Framework Client Profile受以下版本支持:4XNA Framework受以下版本支持:3.0、2.0、1.0请参见 参考Regex 成员 System.Text.RegularExpressions 命名空间 RegexStringValidator 其他资源.NET Framework 正则表达式 正则表达式语言元素 社区内容 添加 常见问题 根据这坛里的链接找到的台湾出品的几篇好贴,感觉很不错,又受到了一次基础培训和巩固复习.所以收藏后也共享给大家,谢谢!QUOTE:Regular Expression 简介中央研究院计算中心ASPAC 计划.tw技术报告: 940191995 年 2 月 9 日Version : 1.0版权声明 目录 Why Regular Expression 组成 Regular Expression 的元素 使用 Regular Expression 时的注意事项 范 例 Appendix : Test using Regular Expression in various environments HP-UX Sun Solaris 2.X AIX 3.2.5 GNU Tools Why Regular ExpressionRegular Expression 是一种字符串表达的方式. 使用者可使用一个简短的 Regular Expression 来表示 具有某特征 或者 复杂难以描述的所有字符串. 而日常数据处理中, 最常进行的工作是从档案中找出具有某特征的字符串, 再加以处理(打印,置换, 计算.). 此时, Regular Expression 便可派上用场. 使用一个简短的 Regular Expression 便可完全指定需要加以处理的资料 , 避免反复判断找寻的困扰. 譬如

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论