基礎語法元字符:
. 表示任意字符(換行符除外)
\w 表示字母、數字、下劃線、漢字。
\W 表示“\w”的補集
\s 表示任意空白字符(包括換行\n、 回車\r、製表\s、垂直製表\v、換頁符\f)
\S 表示"\s"的補集
\d 表示數字
\D 表示非數字
* 表示重複0到多次
例如:以數字開頭,中間有任意個數字,且數字結尾的字符串
string str =@"^\d*$";
Regex.IsMatch(strNum, str);
源代碼:
/***
* 學習基礎元字符
*
* *表示重複0-n次
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace chapter5正則表達式的優勢
{
class Program
{
/// <summary>
/// 表示以數字開頭,中間有任意多個數字,且以數字結尾
/// </summary>
public void Test1()
{
string str = "2345k99";
Console.WriteLine(JudgeNumber(str));
}
/// <summary>
/// 正則表達式方式
/// </summary>
/// <param name="strNum"></param>
/// <returns></returns>
private bool JudgeNumber(string strNum)
{
string strPattern = @"^\d*$";
return Regex.IsMatch(strNum, strPattern);
}
/// <summary>
/// 傳統方式
/// </summary>
/// <param name="strNum"></param>
/// <returns></returns>
private bool JudgeNumberBystring(string strNum)
{
bool isAllNumber = true;
for (int i = 0; i < strNum.Length; i++)
{
if (strNum[i] < '0' || strNum[i] > '9')
{
isAllNumber = false;
break;
}
}
return isAllNumber;
}
public void Test2()
{
string str = "2345gg99";
Console.WriteLine(JudgeNumberBystring(str));
}
public void Test3()
{
}
public void Test4()
{
}
static void Main(string[] args)
{
Program obj = new Program();
obj.Test2();
Console.ReadKey();
}
}
}