c# - 使用正则表达式匹配包含数字字母和破折号的字符串

标签 c# regex .net-3.5

我需要匹配这个字符串 011Q-0SH3-936729 但不是 345376346asfsdfgsfsdf 它必须包含字符、数字和破折号

模式可以是 011Q-0SH3-936729011Q-0SH3-936729-SDF3000-222-AAAA 011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729 我希望它能够匹配其中的任何一个。这样做的原因是我真的不知道格式是否固定而且我也无法找出任何一个所以我需要为具有任意数量的破折号和重复出现任意数量的模式的模式提出一个通用解决方案次。

抱歉,这可能是个愚蠢的问题,但我真的很不擅长正则表达式。

TIA

最佳答案

foundMatch = Regex.IsMatch(subjectString, 
    @"^             # Start of the string
    (?=.*\p{L})     # Assert that there is at least one letter
    (?=.*\p{N})     # and at least one digit
    (?=.*-)         # and at least one dash.
    [\p{L}\p{N}-]*  # Match a string of letters, digits and dashes
    $               # until the end of the string.", 
    RegexOptions.IgnorePatternWhitespace);

应该做你想做的。如果字母/数字你的意思是“只有 ASCII 字母/数字”(而不是国际/Unicode 字母),那么使用

foundMatch = Regex.IsMatch(subjectString, 
    @"^             # Start of the string
    (?=.*[A-Z])     # Assert that there is at least one letter
    (?=.*[0-9])     # and at least one digit
    (?=.*-)         # and at least one dash.
    [A-Z0-9-]*      # Match a string of letters, digits and dashes
    $               # until the end of the string.", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

关于c# - 使用正则表达式匹配包含数字字母和破折号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5191754/

相关文章:

c# - 如何在 Windows Azure 中为 Blob 存储配置 CORS 设置

python - 重复提取文本文件中两个分隔符之间的一行,Python

php - 使用 PHP 将正则表达式替换为正则表达式

c# - 如何让触摸屏在 C# 应用程序中使用鼠标事件而不是触摸事件

c# - 创建 Restsharp 调用以在数组中添加参数

c# - 如何在不使用 HttpContext.Current 的情况下获取 ASP.NET Web 应用程序的物理位置?

c# - 通过 HTTPS 的 HttpWebRequest 的随机问题

c# - 异步且安全地读取文件中的所有行

c# - 在 C# 中序列化和反序列化表达式树

php - 棘手的模式匹配