下面的示例演示如何使用正则表达式来检查字符串是表示货币值还是具有表示货币值的正确格式。在这种情况下,将从用户的当前区域性的 NumberFormatInfo ..::. PositiveSign 属性中动态生成正则表达式。 如果系统的当前区域性为 en-US,导致的正则表达式将是 ^/w*[/+-]?/w?/$?/w?(/d*/.?/d{2}?){1}$.此正则表达式可按下表中所示进行解释。
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 = @"^/w*["; // Get the positive and negative sign symbols. pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + @"]?/w?"; // Get the currency symbol. pattern += Regex.Escape(nfi.CurrencySymbol) + @"?/w?"; // 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.
因为本示例中的正则表达式是动态生成的,所以在设计时我们不知道正则表达式引擎是否可能将当前区域性的货币符号、小数符号或正号及负号错误解释为正则表达式语言运算符。若要防止任何解释错误,本示例将每个动态生成的字符串传递到 Escape 方法。