正则表达式 - C# 中的 2 个字母和 2 个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9639461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:16:40  来源:igfitidea点击:

Regular Expression - 2 letters and 2 numbers in C#

c#regex

提问by Dan-SP

I am trying to develop a regular expression to validate a string that comes to me like: "TE33" or "FR56" or any sequence respecting 2 letters and 2 numbers.

我正在尝试开发一个正则表达式来验证出现在我面前的字符串,例如:“TE33”或“FR56”或任何关于 2 个字母和 2 个数字的序列。

The first 2 characters must be alphabetic and 2 last caracters must be numbers.

前 2 个字符必须是字母,最后 2 个字符必须是数字。

I tried many combinations and I didn't have success. Last one I tried:

我尝试了很多组合,但都没有成功。我试过的最后一个:

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}")){
}

采纳答案by Ry-

You're missing an ending anchor.

你缺少一个结束锚点。

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
    // ...
}

Here's a demo.

这是一个演示。



EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:

编辑:如果您可以在开头的 2 个字母和最后的 2 个数字之间有任何内容:

if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
    // ...
}

Here's a demo.

这是一个演示。

回答by Jason Carter

This should get you for starting with two letters and ending with two numbers.

这应该让您以两个字母开头并以两个数字结尾。

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

如果你知道它总是只有两个和两个,你可以

[A-Za-z]{2}[0-9]{2}

回答by James Hill

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

只是为了好玩,这是一个非正则表达式(对于像我这样的简单者来说更具可读性/可维护性)解决方案:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

编辑

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

看来我误解了要求。下面的代码将确保字符串的前两个字符和后两个字符有效(只要字符串的长度 > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}