首页 > 技术文章 > Regex 构造函数 (String, RegexOptions)

rednuo 2014-04-03 10:46 原文

命名空间:  System.Text.RegularExpressions
程序集:  System(在 System.dll 中)

public Regex(
	string pattern,
	RegexOptions options
)

2、参数

pattern
类型:System.String
要匹配的正则表达式模式。
options
类型:System.Text.RegularExpressions.RegexOptions
用于修改正则表达式的枚举值的按位组合。
异常条件
ArgumentException

出现正则表达式分析错误。

ArgumentNullException

patternnull

ArgumentOutOfRangeException

options 包含无效标志。

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see the .NET Framework 正则表达式 and 正则表达式语言 - 快速参考 topics.

A Regex object is immutable, which means that it can be used only for the match parameters you define when you create it. However, it can be used any number of times without being recompiled.

对调用者的说明

This constructor creates a Regex object that uses the default time-out value of the application domain in which it is created. If a time-out value has not been defined for the application domain, the Regex object uses the value InfiniteMatchTimeout, which prevents the operation from timing out. The recommended constructor for creating a Regex object is Regex.Regex(String, RegexOptions, TimeSpan), which lets you set the time-out interval.

The following example illustrates how to use this constructor to instantiate a regular expression that matches any word that begins with the letters "a" or "t".

 
string pattern = @"\b[at]\w+";
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
string text = "The threaded application ate up the thread pool as it executed.";
MatchCollection matches;

Regex optionRegex = new Regex(pattern, options);
Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString());
// Get matches of pattern in text
matches = optionRegex.Matches(text);
// Iterate matches
for (int ctr = 0; ctr < matches.Count; ctr++)
   Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);


Note that the match collection includes the word "The" that begins the text because the options parameter has defined case-insensitive comparisons.

推荐阅读