命名空間
System.Text.RegularExpressions
常用方法
Regex.IsMatch
public bool IsMatch (string input, string pattern);
在input中是否存在pattern的匹配項。
Regex.Match
public static System.Text.RegularExpressions.Match Match (string input, string pattern);
獲取第一個匹配項乳蓄。在Match的Value中可獲取該項的內(nèi)容溢陪。
Regex.Matches
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern);
獲取所有匹配項
示例
using System;
using System.Text.RegularExpressions;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string[] testStrs = new string[]
{
"123從打abv1234",
"的1234大師565",
"什啊39582的23923的",
"12324的啊是124"
};
string pattern = "[0-9]{3}";
foreach (var str in testStrs)
{
if (Regex.IsMatch(str, pattern))
{
Match match = Regex.Match(str, pattern);
string result = match.Value;
Console.WriteLine(string.Format("{0} 只取匹配到的第一項:{1}", str, result));
MatchCollection matches = Regex.Matches(str, pattern);
Console.WriteLine(string.Format("{0} 共匹配到 {1} 項憋飞。", str, matches.Count));
for (var i = 0; i < matches.Count; i++)
{
Console.WriteLine(string.Format("第{0}項:{1}敏弃。", i, matches[i].Value));
}
Console.WriteLine("……");
}
}
}
}
}