本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译
英语

Regex 类

 

表示不可变的正则表达式。

若要浏览此类型的 .NET Framework 源代码,请参阅引用源

命名空间:   System.Text.RegularExpressions
程序集:  System(位于 System.dll)


[SerializableAttribute]
public class Regex : ISerializable

名称说明
System_CAPS_protmethodRegex()

初始化 Regex 类的新实例。

System_CAPS_protmethodRegex(SerializationInfo, StreamingContext)

使用序列化数据初始化 Regex 类的新实例。

System_CAPS_pubmethodRegex(String)

新实例初始化 Regex 为指定的正则表达式类。

System_CAPS_pubmethodRegex(String, RegexOptions)

新实例初始化 Regex 为指定的正则表达式,用修改模式的选项。

System_CAPS_pubmethodRegex(String, RegexOptions, TimeSpan)

新实例初始化 Regex 为指定的正则表达式,修改模式和一个值,指定多长时间的模式匹配方法的选项的类应进行匹配尝试超时之前。

名称说明
System_CAPS_pubpropertySystem_CAPS_staticCacheSize

获取或设置已编译的正则表达式的当前静态缓存中的最大项数。

System_CAPS_pubpropertyMatchTimeout

获取当前实例的超时间隔。

System_CAPS_pubpropertyOptions

获取已传入的选项 Regex 构造函数。

System_CAPS_pubpropertyRightToLeft

获取一个值,该值指示正则表达式是否从右向左进行搜索。

名称说明
System_CAPS_pubmethodSystem_CAPS_staticCompileToAssembly(RegexCompilationInfo[], AssemblyName)

将一个或多个指定编译 Regex 命名的程序集的对象。

System_CAPS_pubmethodSystem_CAPS_staticCompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])

将一个或多个指定编译 Regex 与具有指定特性名称的程序集的对象。

System_CAPS_pubmethodSystem_CAPS_staticCompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)

将一个或多个指定编译 Regex 对象和指定的资源文件与具有指定特性名称的程序集。

System_CAPS_pubmethodEquals(Object)

确定指定的对象是否等于当前对象。(继承自 Object。)

System_CAPS_pubmethodSystem_CAPS_staticEscape(String)

通过替换为转义码来转义最小的字符集(\、*、+、?、|、{、[、(、)、^、$、.、# 和空白)。 这将指示正则表达式引擎按原义解释这些字符而不是解释为元字符。

System_CAPS_protmethodFinalize()

在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。)

System_CAPS_pubmethodGetGroupNames()

返回正则表达式的捕获组名数组。

System_CAPS_pubmethodGetGroupNumbers()

返回与数组中的组名相对应的捕获组号的数组。

System_CAPS_pubmethodGetHashCode()

作为默认哈希函数。(继承自 Object。)

System_CAPS_pubmethodGetType()

获取当前实例的 Type(继承自 Object。)

System_CAPS_pubmethodGroupNameFromNumber(Int32)

获取与指定组号相对应的组名。

System_CAPS_pubmethodGroupNumberFromName(String)

返回与指定组名相对应的组号。

System_CAPS_protmethodInitializeReferences()

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_pubmethodIsMatch(String)

该值指示是否在指定的正则表达式 Regex 构造函数指定的输入字符串中找到的匹配项。

System_CAPS_pubmethodIsMatch(String, Int32)

该值指示是否在指定的正则表达式 Regex 构造函数从字符串中的指定起始位置开始对指定输入字符串中找到的匹配项。

System_CAPS_pubmethodSystem_CAPS_staticIsMatch(String, String)

指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项。

System_CAPS_pubmethodSystem_CAPS_staticIsMatch(String, String, RegexOptions)

指示所指定的正则表达式是否使用指定的匹配选项在指定的输入字符串中找到了匹配项。

System_CAPS_pubmethodSystem_CAPS_staticIsMatch(String, String, RegexOptions, TimeSpan)

指示所指定的正则表达式是否使用指定的匹配选项和超时间隔在指定的输入字符串中找到了匹配项。

System_CAPS_pubmethodMatch(String)

搜索指定的输入的字符串中指定的正则表达式的第一个匹配项 Regex 构造函数。

System_CAPS_pubmethodMatch(String, Int32)

从输入字符串中的指定起始位置开始,在该字符串中搜索正则表达式的第一个匹配项。

System_CAPS_pubmethodMatch(String, Int32, Int32)

从指定的起始位置开始,在输入字符串中搜索正则表达式的第一个匹配项,并且仅搜索指定数量的字符。

System_CAPS_pubmethodSystem_CAPS_staticMatch(String, String)

在指定的输入字符串中搜索指定的正则表达式的第一个匹配项。

System_CAPS_pubmethodSystem_CAPS_staticMatch(String, String, RegexOptions)

使用指定的匹配选项在输入字符串中搜索指定的正则表达式的第一个匹配项。

System_CAPS_pubmethodSystem_CAPS_staticMatch(String, String, RegexOptions, TimeSpan)

使用指定的匹配选项和超时间隔在输入字符串中搜索指定的正则表达式的第一个匹配项。

System_CAPS_pubmethodMatches(String)

在指定的输入字符串中搜索正则表达式的所有匹配项。

System_CAPS_pubmethodMatches(String, Int32)

从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。

System_CAPS_pubmethodSystem_CAPS_staticMatches(String, String)

在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

System_CAPS_pubmethodSystem_CAPS_staticMatches(String, String, RegexOptions)

使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

System_CAPS_pubmethodSystem_CAPS_staticMatches(String, String, RegexOptions, TimeSpan)

使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。

System_CAPS_protmethodMemberwiseClone()

创建当前 Object 的浅表副本。(继承自 Object。)

System_CAPS_pubmethodReplace(String, MatchEvaluator)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。

System_CAPS_pubmethodReplace(String, MatchEvaluator, Int32)

在指定的输入字符串替换与正则表达式模式匹配与返回的字符串的字符串指定的最大 MatchEvaluator 委托。

System_CAPS_pubmethodReplace(String, MatchEvaluator, Int32, Int32)

在指定的输入子字符串替换与正则表达式模式匹配与返回的字符串的字符串指定的最大 MatchEvaluator 委托。

System_CAPS_pubmethodReplace(String, String)

在指定的输入字符串内,使用指定的替换字符串替换与某个正则表达式模式匹配的所有的字符串。

System_CAPS_pubmethodReplace(String, String, Int32)

在指定输入字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。

System_CAPS_pubmethodReplace(String, String, Int32, Int32)

在指定输入子字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, MatchEvaluator)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, MatchEvaluator, RegexOptions)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。 指定的选项将修改匹配操作。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有子字符串。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, String)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, String, RegexOptions)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。 指定的选项将修改匹配操作。

System_CAPS_pubmethodSystem_CAPS_staticReplace(String, String, String, RegexOptions, TimeSpan)

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。

System_CAPS_pubmethodSplit(String)

将输入的字符串拆分为一个定义在由正则表达式模式中指定的位置的子字符串数组 Regex 构造函数。

System_CAPS_pubmethodSplit(String, Int32)

输入字符串拆分为指定的最大次数的子字符串,定义正则表达式中指定的位置的数组 Regex 构造函数。

System_CAPS_pubmethodSplit(String, Int32, Int32)

输入字符串拆分为指定的最大次数的子字符串,定义正则表达式中指定的位置的数组 Regex 构造函数。 从输入字符串的指定字符位置开始搜索正则表达式模式。

System_CAPS_pubmethodSystem_CAPS_staticSplit(String, String)

在由正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。

System_CAPS_pubmethodSystem_CAPS_staticSplit(String, String, RegexOptions)

在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。 指定的选项将修改匹配操作。

System_CAPS_pubmethodSystem_CAPS_staticSplit(String, String, RegexOptions, TimeSpan)

在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。

System_CAPS_pubmethodToString()

返回传入的正则表达式模式 Regex 构造函数。(覆盖 Object.ToString()。)

System_CAPS_pubmethodSystem_CAPS_staticUnescape(String)

转换输入字符串中的任何转义字符。

System_CAPS_protmethodUseOptionC()

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protmethodUseOptionR()

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protmethodSystem_CAPS_staticValidateMatchTimeout(TimeSpan)

此 API 支持 产品 基础结构,不应从代码直接使用。 检查超时间隔是否在可接受的范围内。

名称说明
System_CAPS_protfieldcapnames

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protfieldcaps

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protfieldcapsize

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protfieldcapslist

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protfieldfactory

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_pubfieldSystem_CAPS_staticInfiniteMatchTimeout

指定模式匹配操作不应超时。

System_CAPS_protfieldinternalMatchTimeout

此 API 支持 产品 基础结构,不应从代码直接使用。 操作超时之前在一个模式匹配操作中可以经过的最长时间。

System_CAPS_protfieldpattern

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

System_CAPS_protfieldroptions

此 API 支持 产品 基础结构,不应从代码直接使用。 使用 Regex 对象生成的 CompileToAssembly 方法。

名称说明
System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)

此 API 支持 产品 基础结构,不应从代码直接使用。 使用所需的数据填充 SerializationInfo 对象来反序列化当前 Regex 对象。

System_CAPS_note说明

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#System/regex/system/text/regularexpressions/Regex.cs#bbe3b2eb80ae5526. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.Text.RegularExpressions.Regex class represents the .NET Framework's regular expression engine. It can be used to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.

System_CAPS_note说明

If your primary interest is to validate a string by determining whether it conforms to a particular pattern, you can use the T:System.Configuration.RegexStringValidator class.

To use regular expressions, you define the pattern that you want to identify in a text stream by using the syntax documented in Regular Expression Language Elements. Next, you can optionally instantiate a T:System.Text.RegularExpressions.Regex object. Finally, you call a method that performs some operation, such as replacing text that matches the regular expression pattern, or identifying a pattern match.

System_CAPS_note说明

For some common regular expression patterns, see Regular Expression Examples. There are also a number of online libraries of regular expression patterns, such as the one at Regular-Expressions.infohttp://www.regular-expressions.info/examples.html.


For more information about using the T:System.Text.RegularExpressions.Regex class, see the following sections in this topic:

For more information about the regular expression language, see Regular Expression Language Elements or download and print one of these brochures:

      Quick Reference in Word (.docx) formathttp://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular expressions quick reference.docx       Quick Reference in PDF (.pdf) formathttp://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular expressions quick reference.pdf

The T:System.String class includes several search and comparison methods that you can use to perform pattern matching with text. For example, the M:System.String.Contains(System.String), M:System.String.EndsWith(System.String), and M:System.String.StartsWith(System.String) methods determine whether a string instance contains a specified substring; and the M:System.String.IndexOf(System.String), M:System.String.IndexOfAny(System.Char[]), M:System.String.LastIndexOf(System.String), and M:System.String.LastIndexOfAny(System.Char[],System.Int32,System.Int32) methods return the starting position of a specified substring in a string. Use the methods of the T:System.String class when you are searching for a specific string. Use the T:System.Text.RegularExpressions.Regex class when you are searching for a specific pattern in a string. For more information and examples, see .NET Framework Regular Expressions.

Back to Remarks

After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways:

  • By instantiating a T:System.Text.RegularExpressions.Regex object that represents the regular expression. To do this, you pass the regular expression pattern to a M:System.Text.RegularExpressions.Regex.#ctor(System.String) constructor. A T:System.Text.RegularExpressions.Regex object is immutable; when you instantiate a T:System.Text.RegularExpressions.Regex object with a regular expression, that object's regular expression cannot be changed.

  • By supplying both the regular expression and the text to search to a static (Shared in Visual Basic) T:System.Text.RegularExpressions.Regex method. This enables you to use a regular expression without explicitly creating a T:System.Text.RegularExpressions.Regex object.

All T:System.Text.RegularExpressions.Regex pattern identification methods include both static and instance overloads.

The regular expression engine must compile a particular pattern before the pattern can be used. Because T:System.Text.RegularExpressions.Regex objects are immutable, this is a one-time procedure that occurs when a T:System.Text.RegularExpressions.Regex class constructor or a static method is called. To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods.

System_CAPS_important重要事项

In the .NET Framework versions 1.0 and 1.1, all compiled regular expressions, whether they were used in instance or static method calls, were cached. Starting with the .NET Framework 2.0, only regular expressions used in static method calls are cached.

However, caching can adversely affect performance in the following two cases:

  • When you use static method calls with a large number of regular expressions. By default, the regular expression engine caches the 15 most recently used static regular expressions. If your application uses more than 15 static regular expressions, some regular expressions must be recompiled. To prevent this recompilation, you can increase the P:System.Text.RegularExpressions.Regex.CacheSize property.

  • When you instantiate new T:System.Text.RegularExpressions.Regex objects with regular expressions that have previously been compiled. For example, the following code defines a regular expression to locate duplicated words in a text stream. Although the example uses a single regular expression, it instantiates a new T:System.Text.RegularExpressions.Regex object to process each line of text. This results in the recompilation of the regular expression with each iteration of the loop.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    

    To prevent recompilation, you should instantiate a single T:System.Text.RegularExpressions.Regex object that is accessible to all code that requires it, as shown in the following rewritten example.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
    
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    

Back to Remarks

Whether you decide to instantiate a T:System.Text.RegularExpressions.Regex object and call its methods or call static methods, the T:System.Text.RegularExpressions.Regex class offers the following pattern-matching functionality:

  • Validation of a match. You call the Overload:System.Text.RegularExpressions.Regex.IsMatch method to determine whether a match is present.

  • Retrieval of a single match. You call the Overload:System.Text.RegularExpressions.Regex.Match method to retrieve a T:System.Text.RegularExpressions.Match object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the M:System.Text.RegularExpressions.Match.NextMatch method.

  • Retrieval of all matches. You call the Overload:System.Text.RegularExpressions.Regex.Matches method to retrieve a T:System.Text.RegularExpressions.MatchCollection object that represents all the matches found in a string or in part of a string.

  • Replacement of matched text. You call the Overload:System.Text.RegularExpressions.Regex.Replace method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the Overload:System.Text.RegularExpressions.Regex.Replace methods include a T:System.Text.RegularExpressions.MatchEvaluator parameter that enables you to programmatically define the replacement text.

  • Creation of a string array that is formed from parts of an input string. You call the Overload:System.Text.RegularExpressions.Regex.Split method to split an input string at positions that are defined by the regular expression.

In addition to its pattern-matching methods, the T:System.Text.RegularExpressions.Regex class includes several special-purpose methods:

  • The M:System.Text.RegularExpressions.Regex.Escape(System.String) method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string.

  • The M:System.Text.RegularExpressions.Regex.Unescape(System.String) method removes these escape characters.

  • The Overload:System.Text.RegularExpressions.Regex.CompileToAssembly method creates an assembly that contains predefined regular expressions. The .NET Framework contains examples of these special-purpose assemblies in the N:System.Web.RegularExpressions namespace.

Back to Remarks

The .NET Framework supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. However, the power and flexibility come at a cost: the risk of poor performance. Regular expressions that perform poorly are surprisingly easy to create. In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. For more information about the .NET Framework regular expression engine, see Details of Regular Expression Behavior. For more information about excessive backtracking, see Backtracking.

Starting with the net_v45, you can define a time-out interval for regular expression matches. If the regular expression engine cannot identify a match within this time interval, the matching operation throws a T:System.Text.RegularExpressions.RegexMatchTimeoutException exception. In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. It also could indicate, however, that the timeout interval has been set too low, or that the current machine load has caused an overall degradation in performance.

How you handle the exception depends on the cause of the exception. If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern.

You can set a time-out interval by calling the M:System.Text.RegularExpressions.Regex.#ctor(System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan) constructor when you instantiate a regular expression object. For static methods, you can set a time-out interval by calling an overload of a matching method that has a matchTimeout parameter. If you do not set a time-out value explicitly, the default time-out value is determined as follows:

  • By using the application-wide time-out value, if one exists. This can be any time-out value that applies to the application domain in which the T:System.Text.RegularExpressions.Regex object is instantiated or the static method call is made. You can set the application-wide time-out value by calling the M:System.AppDomain.SetData(System.String,System.Object) method to assign the string representation of a T:System.TimeSpan value to the "REGEX_DEFAULT_MATCH_TIMEOUT" property.

  • By using the value F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout, if no application-wide time-out value has been set.

System_CAPS_important重要事项

We recommend that you set a time-out value in all regular expression pattern-matching operations. For more information, see Best Practices for Regular Expressions in the .NET Framework.

Back to Remarks

The following example uses a regular expression to check for repeated occurrences of words in a string. The regular expression \b(?<word>\w+)\s+(\k<word>)\b can be interpreted as shown in the following table.

Pattern

Description

\b

Start the match at a word boundary.

(?<word>\w+)

Match one or more word characters up to a word boundary. Name this captured group word.

\s+

Match one or more white-space characters.

(\k<word>)

Match the captured group that is named word.

\b

Match a word boundary.

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

The following example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. In this case, the regular expression is built dynamically from the P:System.Globalization.NumberFormatInfo.CurrencyDecimalSeparator, P:System.Globalization.NumberFormatInfo.CurrencyDecimalDigits, P:System.Globalization.NumberFormatInfo.CurrencySymbol, P:System.Globalization.NumberFormatInfo.NegativeSign, and P:System.Globalization.NumberFormatInfo.PositiveSign properties for the user's current culture. If the system's current culture is en-US, the resulting regular expression is ^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$. This regular expression can be interpreted as shown in the following table.

Pattern

Description

^

Start at the beginning of the string.

\s*

Match zero or more white-space characters.

[\+-]?

Match zero or one occurrence of either the positive sign or the negative sign.

\s?

Match zero or one white-space character.

\$?

Match zero or one occurrence of the dollar sign.

\s?

Match zero or one white-space character.

\d*

Match zero or more decimal digits.

\.?

Match zero or one decimal point symbol.

\d{2}?

Match two decimal digits zero or one time.

(\d*\.?\d{2}?){1}

Match the pattern of integral and fractional digits separated by a decimal point symbol at least one time.

$

Match the end of the string.

In this case, the regular expression assumes that a valid currency string does not contain group separator symbols, and that it has either no fractional digits or the number of fractional digits defined by the current culture's P:System.Globalization.NumberFormatInfo.CurrencyDecimalDigits property.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get the current NumberFormatInfo object to build the regular 
      // expression pattern dynamically.
      NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;

      // Define the regular expression pattern.
      string pattern; 
      pattern = @"^\s*[";
      // Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + @"]?\s?";
      // Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + @"?\s?";
      // Add integral digits to the pattern.
      pattern += @"(\d*";
      // Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?";
      // Add the fractional digits.
      pattern += @"\d{";
      // Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$";

      Regex rgx = new Regex(pattern);

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

      // Check each test string against the regular expression.
      foreach (string test in tests)
      {
         if (rgx.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:
//       -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 a currency value.
//       0.34 is a currency value.
//       1,052.21 is not a currency value.
//       $10.62 is a currency value.
//       +1.43 is a currency value.
//       -$0.23 is a currency value.

Because the regular expression in this example is built dynamically, we do not know at design time whether the current culture's currency symbol, decimal sign, or positive and negative signs might be misinterpreted by the regular expression engine as regular expression language operators. To prevent any misinterpretation, the example passes each dynamically generated string to the M:System.Text.RegularExpressions.Regex.Escape(System.String) method.

通用 Windows 平台
自 8 起可用
.NET Framework
自 1.1 起可用
可移植类库
可移植 .NET 平台 中受支持
Silverlight
自 2.0 起可用
Windows Phone Silverlight
自 7.0 起可用
Windows Phone
自 8.1 起可用

The T:System.Text.RegularExpressions.Regex class is immutable (read-only) and thread safe. T:System.Text.RegularExpressions.Regex objects can be created on any thread and shared between threads. For more information, see [<topic://cpconThreadSafety>].

返回页首
显示: