帮助对c#中的文本字符串进行正则表达式验证

时间:2022-09-13 07:47:33

im trying to validate a string of text that must be in the following format,

我试图验证必须采用以下格式的文本字符串,

The number "1" followed by a semicolon followed by between 1 and three numbers only - it would look something like this.

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

1:1 (correct)
1:34 (correct)
1:847 (correct)
1:2322 (incorrect)

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

There can be no letters or anything else except numbers.

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

Does anyone know how i can make this with REGEX? and in C#

有谁知道我怎么能用REGEX做到这一点?在C#

1 个解决方案

#1


7  

The following pattern would do that for you:

以下模式将为您做到这一点:

^1:\d{1,3}$

Sample code:

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

For more convenient access you should probably put the validation into a separate method:

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

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

Explanation of the pattern:

模式说明:

^     - 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

The ^ and $ characters makes the pattern match the full string, instead of finding valid strings embedded in a larger string. Without them the pattern would also match strings like "1:2322" and "the scale is 1:234, which is unusual".

^和$字符使模式匹配完整字符串,而不是查找嵌入在较大字符串中的有效字符串。没有它们,模式也会匹配像“1:2322”和“比例是1:234,这是不寻常的”之类的字符串。

#1


7  

The following pattern would do that for you:

以下模式将为您做到这一点:

^1:\d{1,3}$

Sample code:

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

For more convenient access you should probably put the validation into a separate method:

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

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

Explanation of the pattern:

模式说明:

^     - 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

The ^ and $ characters makes the pattern match the full string, instead of finding valid strings embedded in a larger string. Without them the pattern would also match strings like "1:2322" and "the scale is 1:234, which is unusual".

^和$字符使模式匹配完整字符串,而不是查找嵌入在较大字符串中的有效字符串。没有它们,模式也会匹配像“1:2322”和“比例是1:234,这是不寻常的”之类的字符串。