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(有很多实用的例子)