在C#中,如何对文本字符串进行正则表达式验证?

4

我正在尝试验证一个文本字符串,它必须采用以下格式:

数字“1”后跟一个分号,然后是1到3个数字 - 它看起来像这样。

1:1(正确)
1:34(正确)
1:847(正确)
1:2322(不正确)

除了数字,不能有任何字母或其他内容。

是否有人知道如何使用REGEX实现这一点?并使用C#。

1个回答

7
以下模式可以帮助您实现这一点:
^1:\d{1,3}$

示例代码:

string pattern = @"^1:\d{1,3}$";
Console.WriteLine(Regex.IsMatch("1:1", pattern)); // true
Console.WriteLine(Regex.IsMatch("1:34", pattern)); // true
Console.WriteLine(Regex.IsMatch("1:847", pattern)); // true
Console.WriteLine(Regex.IsMatch("1:2322", pattern)); // false

为了更方便地访问,您应该将验证放入单独的方法中:

private static bool IsValid(string input)
{
    return Regex.IsMatch(input, @"^1:\d{1,3}$", RegexOptions.Compiled);
}

模式的解释:

^     - the start of the string
1     - the number '1'
:     - a colon
\d    - any decimal digit
{1,3} - at least one, not more than three times
$     - the end of the string
^$字符使模式匹配整个字符串,而不是在较大的字符串中查找有效字符串。如果没有它们,模式也会匹配像"1:2322""the scale is 1:234, which is unusual"这样的字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接