c#正则表达式验证字符串

下面的代码示例演示如何使用正则表达式检查字符串是否具有表示货币值的正确格式。注意,如果使用 ^$ 封闭标记,则指示整个字符串(而不只是子字符串)都必须匹配正则表达式。

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);
              }
          }
        
    }    
}
 



上一篇: 常用正则表达式
下一篇: C# 如何将string 转换为 Color 类型
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: c#
相关日志:
评论: 0 | 引用: 0 | 查看次数: 4475
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑