Gra*_*ant 4 c# regex string validation text
我试图验证必须采用以下格式的文本字符串,
数字"1"后跟一个分号,后跟1到3个数字 - 它看起来像这样.
1:1(正确)
1:34(正确)
1:847(正确)
1:2322(不正确)
除了数字之外,不能有任何字母或其他内容.
有谁知道如何用REGEX做到这一点?并在C#
以下模式可以帮到您:
^1:\d{1,3}$
Run Code Online (Sandbox Code Playgroud)
示例代码:
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
Run Code Online (Sandbox Code Playgroud)
为了更方便地访问,您应该将验证放入单独的方法中:
private static bool IsValid(string input)
{
return Regex.IsMatch(input, @"^1:\d{1,3}$", RegexOptions.Compiled);
}
Run Code Online (Sandbox Code Playgroud)
模式说明:
^ - 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
Run Code Online (Sandbox Code Playgroud)
在^和$人物,使图案完整的字符串匹配,而不是找到嵌入在一个更大的字符串有效字符串.没有它们,模式也会匹配像"1:2322"和的字符串"the scale is 1:234, which is unusual".