1。在Regex中定義變數並調用:
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.", matches.Count);
// Report on each match.
foreach (Match match in matches)
{
string word = match.Groups["word"].Value;
int index = match.Index;
Console.WriteLine("{0} repeated at position {1}", word, index);
}
}
}
其中?<word>定義了一個變數,之後的\k<word>調用自身定義的變數word。
2。好用的Regex.Replace 和Match.Result
這個例子實現輸入的日期更改格式的功能,用Regex自動搜尋字串並替換,注意Regex中變數的使用。public string MDYToDMY(string input)
{
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
Match.Result是返回一個可以帶Regex中變數值的字串。public string Extension(string url)
{
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
RegexOptions.Compiled);
return r.Match(url).Result("${proto}${port}");
}
正則式官方詳解:
http://msdn.microsoft.com/zh-cn/library/ae5bf541.aspx