Regular Expression in C#

Essential Code to Use Regular Expression in C#

 

using System;

using System.Text.RegularExpressions;

 

           Regex phoneExp = new Regex(@"^\(\d{3}\)\s\d{3}-\d{4}$");

            string input;

            Console.Write("Enter a phone number: ");

            input = Console.ReadLine();

            while (phoneExp.Match(input).Success == false)
            {

                Console.WriteLine("Invalid input. Try again.");

                Console.Write("Enter a phone number: ");

                input = Console.ReadLine();
            }

            Console.WriteLine("Validated!");
   

[2]里还介绍了使用RE来进行replace和遍历匹配的字符串的代码.


 附

Regular Expression Single Character Classes

Class

Description

\d

Any digit

\D

Any nondigit

\w

Any word character

\W

Any nonword character

\s

Any whitespace character

\SW

Any nonwhitespace

 


Ranged and Set Character Classes

Format

Description

.

Any character except newline.

\p{uc}

Any character within the Unicode character category uc.

[abcxyz]

Any literal character in the set.

\P{uc}

Any character not within the Unicode character category uc.

[^abcxyz]

Any character not in the set of literal characters.

 


Character Class Quantifiers

Format

Description

*

0 or more characters

+

1 or more characters

?

0 or 1 characters

{n}

Exactly n characters

{n,}

At least n characters

{n,m}

At least n but no more than m characters

 


Positional (Atomic Zero-Width) Assertions

Format

Description

^

Beginning of a string or beginning of a newline

\z

End of the string, including the newline character

$

End of a string before a newline character or at the end of the line

\G

Continues where the last match left off

\A

Beginning of a string

\b

Between word boundaries (between alphanumeric and nonalphanumeric characters)

\Z

End of the string before the newline character

\B

Characters not between word boundaries

 


Reference
[1] http://www.codeproject.com/dotnet/regextutorial.asp
The 30 Minute Regex Tutorial (from codeproject) (
用实例介绍书写正则表达式的技巧 , 并提供了一个非常好的工具 Expresso( 甚至可以帮你分析你写的正则表达式 ))

[2] http://www.codeproject.com/books/0672325802.asp

Strings and Regular Expressions (chapter 3 of Microsoft Visual C# .NET 2003 Developer's Cookbook) (C#RE的基本知识,基本的使用代码)

[3] http://msdn2.microsoft.com/en-us/library/system.text.regularexpressions.aspx

System.Text.RegularExpressions Namespace (.net framework中正则表达式有关的类,Regex, Match,RegexOptions)

[4] http://www.ultrapico.com/

download the latest Expresso (an easy tool to learn regular expression)

 

[5] http://msdn2.microsoft.com/en-US/library/hs600312.aspx

.NET Framework Regular Expressions(有很多实用的例子)

转载于:https://www.cnblogs.com/yuquanlaobo/archive/2007/01/17/622876.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值