c#正则表达式验证字符串
作者:admin 日期:2009-01-06
下面的代码示例演示如何使用正则表达式检查字符串是否具有表示货币值的正确格式。注意,如果使用 ^ 和 $ 封闭标记,则指示整个字符串(而不只是子字符串)都必须匹配正则表达式。
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);
}
}
}
}
广告位