Regex 类包含若干静态方法,使您无需显式创建 Regex 对象即可使用正则表达式。使用静态方法等效于构造 Regex 对象,使用该对象一次然后将其销毁。
Regex 类是不可变(只读)的,并且具有固有的线程安全性。可以在任何线程上创建 Regex 对象,并在线程间共享。
面的代码示例演示如何使用正则表达式检查字符串是否具有表示货币值的正确格式。注意,如果使用 ^
和 $
封闭标记,则指示整个字符串(而不只是子字符串)都必须匹配正则表达式。
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"};
// 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);
}
}
}
}
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"};
// 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);
}
}
}
}
下面的代码示例演示如何使用正则表达式检查字符串中重复出现的词。注意如何使用 (?<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.", 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);
}
}
}
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);
}
}
}