c# - 正则表达式匹配重复出现的模式

标签 c# regex

我想使用正则表达式验证 C# TextBox 中的输入。预期的输入格式如下: CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-C

所以我得到了六个元素,其中五个分隔字符和最后一个分隔字符。

现在我的正则表达式匹配 5 到 255 个字符之间的任何字符:.{5,255}

我需要如何修改它才能匹配上面提到的格式?

最佳答案

更新:-

如果你想匹配任何字符,那么你可以使用:-

^(?:[a-zA-Z0-9]{5}-){6}[a-zA-Z0-9]$

解释:-

(?:                // Non-capturing group
    [a-zA-Z0-9]{5} // Match any character or digit of length 5
    -              // Followed by a `-`
){6}               // Match the pattern 6 times (ABCD4-) -> 6 times
[a-zA-Z0-9]        // At the end match any character or digit.

注意:- 下面的正则表达式只会匹配您发布的模式:-

CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-C

你可以试试这个正则表达式:-

^(?:([a-zA-Z0-9])\1{4}-){6}\1$

解释:-

(?:                // Non-capturing group
  (                // First capture group
    [a-zA-Z0-9]    // Match any character or digit, and capture in group 1
  )
  \1{4}            // Match the same character as in group 1 - 4 times
  -                // Followed by a `-`
){6}               // Match the pattern 6 times (CCCCC-) -> 6 times
\1                 // At the end match a single character.

关于c# - 正则表达式匹配重复出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004180/

相关文章:

c# - 超时正在触发,但应用程序继续正常运行

regex - Play Framework 缓存删除匹配正则表达式的元素

java string.replaceFirst/string.replaceLast 正则表达式从末尾删除第二个斜杠后的所有内容

javascript - 使用 RegEx 获取用大括号括起来并转义的字符串

javascript - 简单电话 RegXP 返回 : Uncaught SyntaxError: Invalid or unexpected token

c# - 如何在 wpf 文本框中自动完成?

c# - 手动销毁 C# 对象

c# - 检查 boolean 数组中的元素值 - C#

Java正则表达式模式匹配

c# - WinForms 如何强制执行线程亲和性?