.NET 中的正則表達式

作者: ariesy  來源: kunzhu.co.cc  發布時間: 2010-11-02 15:11  閱讀: 17068 次  推薦: 4   原文鏈接   [收藏]  

前兩天面試一個程序員,自己說工作中用到過正則表達式,也比較熟悉,問他要使用正則表達式需要引用那個命名空間,使用哪些類,居然吱吱唔唔答不上來,讓他寫一個驗證電話號碼的正則表達式也寫不出來,實在是很奇怪這種程序員是怎么工作了兩三年的。

言歸正傳,下面介紹下.net中正則表達式中的使用。

要在.net中使用正則表達式,需要引用System.Text.RegularExpressions 命名空間。新建一個正則表達式類:

 
string pattern = "some_pattern"; //正則表達式字符串
Regex regex = new Regex(pattern);

使用正則表達式匹配字符串

 
string input = "some_input";
Match match
= regex.Match(input);
MatchCollection matches
= regex.Matches(input);
bool isMatch = regex.IsMatch(input);

Match方法返回單個的精確匹配結果,Matches返回所有的匹配結果的一個Match類的集合,IsMatch方法返回是否能夠匹配輸入字符串的一個bool結果。

Match類是一個保持匹配結果的類,它有一個成員Groups,是一個保存Group class的集合類。

Group 表示單個捕獲組的結果。由于存在數量詞,一個捕獲組可以在單個匹配中捕獲零個、一個或更多的字符串,因此 Group 提供 Capture 對象的集合。

Capture 表示單個成功捕獲中的一個子字符串。

Group從Capture繼承,表示單個捕獲組的最后一個字符串。

即對于一個Group 類的實例對象group:

int captureCount = group.Captures.Count;

則group.Value與group.Captures[captureCount - 1].Value是相等的。

以下是幾個正則表達式的使用樣例:

使用正則表達式檢查字符串是否具有表示貨幣值的正確格式。

 

代碼
 
using System;
using System.Text.RegularExpressions;

public class Test
{

public static void Main ()
{

// Define a regular expression for currency values.
Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");

// Define some test strings.
string[] tests = {"-42", "19.99", "0.001", "100 USD",
".34", "0.34", "1,052.21"};

// Check each test string against the regular expression.
foreach (string test in tests)
{

if (rx.IsMatch(test))
{
Console.WriteLine(
"{0} is a currency value.", test);
}

else
{
Console.WriteLine(
"{0} is not a currency value.", test);
}
}
}
}

// The example displays the following output to the console:
// -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 not a currency value.
// 0.34 is a currency value.
// 1,052.21 is not a currency value.

 

使用正則表達式檢查字符串中重復出現的詞。

 

 

 
using System;
using System.Text.RegularExpressions;

public class Test
{


public static void Main ()
{


// Define a regular expression for repeated words.
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
RegexOptions.Compiled
| RegexOptions.IgnoreCase);

// Define a test string.
string text = "The the quick brown fox fox jumped over the lazy dog
dog.";

// Find matches.
MatchCollection matches = rx.Matches(text);

// Report the number of matches found.
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);


// Report on each match.
foreach (Match match in matches)
{
GroupCollection groups
= match.Groups;
Console.WriteLine(
"'{0}' repeated at positions {1} and {2}",
groups[
"word"].Value,
groups[
0].Index,
groups[
1].Index);
}

}

}

// 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

使用 Capture 對象在控制臺中顯示每個正則表達式匹配項組的成員。

 

代碼
 
string text = "One fish two fish red fish blue fish";
string pat = @"(?<1>\w+)\s+(?<2>fish)\s*";
// Compile the regular expression.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
while (m.Success)
{

// Display the first match and its capture set.
System.Console.WriteLine("Match=[" + m + "]");
CaptureCollection cc
= m.Captures;
foreach (Capture c in cc)
{
System.Console.WriteLine(
"Capture=[" + c + "]");
}

// Display Group1 and its capture set.
Group g1 = m.Groups[1];
System.Console.WriteLine(
"Group1=[" + g1 + "]");
foreach (Capture c1 in g1.Captures)
{
System.Console.WriteLine(
"Capture1=[" + c1 + "]");
}

// Display Group2 and its capture set.
Group g2 = m.Groups[2];
System.Console.WriteLine(
"Group2=["+ g2 + "]");
foreach (Capture c2 in g2.Captures)
{
System.Console.WriteLine(
"Capture2=[" + c2 + "]");
}

// Advance to the next match.
m = m.NextMatch();
}

// The example displays the following output:
// Match=[One fish ]
// Capture=[One fish ]
// Group1=[One]
// Capture1=[One]
// Group2=[fish]
// Capture2=[fish]
// Match=[two fish ]
// Capture=[two fish ]
// Group1=[two]
// Capture1=[two]
// Group2=[fish]
// Capture2=[fish]
// Match=[red fish ]
// Capture=[red fish ]
// Group1=[red]
// Capture1=[red]
// Group2=[fish]
// Capture2=[fish]
// Match=[blue fish]
// Capture=[blue fish]
// Group1=[blue]
// Capture1=[blue]
// Group2=[fish]
// Capture2=[fish]

 

 

4
0
 
標簽:regular
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()