c# - 如何检查字符串是否包含一定数量的字母和数字 C#

标签 c#

我想看看一个字符串是否包含 3 个字母 + 2 个数字 + 1 个字母或数字。这是当今瑞典车牌的标准。

是否可以查看字符串是否符合标准 ABC123 或 ABC12D 并且最好按该顺序? 如何尽可能简单地做到这一点?

if(theString.Length == 6)
{
    if(theString.Contains(...)
    {

最佳答案

你应该为此使用正则表达式:

Regex r = new Regex("^[A-Z]{3}[0-9]{3}$");
// ^ start of string
// [A-Z] a letter
// {3} 3 times
// [0-9] a number
// {3} 3 times
// $ end of string

string correct = "ABC123";
string wrong = "ABC12B";

Console.WriteLine(correct + ": " + (r.IsMatch(correct) ? "correct" : "wrong"));
Console.WriteLine(wrong + ": " + (r.IsMatch(wrong) ? "correct" : "wrong"));

// If last character can also be a letter:
r = new Regex("^[A-Z]{3}[0-9]{2}[0-9A-Z]$");
// ^ start of string
// [A-Z] a letter
// {3} 3 times
// [0-9A-Z] a number
// {2} 2 times
// [0-9A-Z] A letter or a number
// $ end of string

Console.WriteLine(correct + ": " + (r.IsMatch(correct) ? "correct" : "wrong"));
Console.WriteLine(wrong + ": " + (r.IsMatch(wrong) ? "correct" : "wrong"));

关于c# - 如何检查字符串是否包含一定数量的字母和数字 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417138/

相关文章:

C# LDAP 查询以获取特定组中用户的管理员

c# - 数组内部的 String.Format

c# - 如何在 Active Directory 中对密码更改进行客户端验证

c# - 动态改变鼠标速度

c# - 如何在 Xamarin 表单中使用 MVVM 仅为 Collection View 中的选定框架设置颜色?

c# - 重定向到当前友好的 URL(有或没有 url 变量)

c# - 自定义 Log4Net 过滤器级别不写入日志

c# - 使用缓存机制进行节流有问题吗?

c# - 在 docker run 上找不到 appsettings.json 文件问题

c# - 使用 C# 代码格式化完整地址