博客 (12)

下面的代码示例演示如何使用正则表达式检查字符串是否具有表示货币值的正确格式。注意,如果使用 ^ 和 $ 封闭标记,则指示整个字符串(而不只是子字符串)都必须匹配正则表达式。

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.

下面的代码示例演示如何使用正则表达式检查字符串中重复出现的词。注意如何使用 (?<word>) 构造来命名组,以及稍后如何使用 (\k<word>)在表达式中引用该组。

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

正则取值

string text = this.textBox1.Text;
MatchCollection mats = Regex.Matches(text, "<a href=\"http://blog.csdn.net/(?<user>[^/]*)/category/(?<catalog>[^\\.]*).aspx\">(?<typetitle>[^<>]*)</a>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
foreach (Match mat in mats)
{
MessageBox.Show(mat.Groups["user"].Value + "--" + mat.Groups["catalog"].Value + mat.Groups["typetitle"].Value + mat.Value);
}
5,719