正则表达式的内容(一)

  下面的示例演示如何使用正则表达式来检查字符串是表示货币值还是具有表示货币值的正确格式。在这种情况下,将从用户的当前区域性的 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. 发表于 @ 2011年04月15日 13:39:00 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值