我想使用正则表达式验证C#TextBox中的输入。预期输入采用以下格式:
CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-CCCCC-C
所以我有六个元素,分别是五个分开的字符和一个分开的字符。
现在我的正则表达式匹配5到255个字符之间的任何字符:.{5,255}
如何修改它以匹配上述格式?
答案 0 :(得分:3)
更新: -
如果你想匹配任何角色,那么你可以使用: -
^(?:[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.
答案 1 :(得分:1)
未经测试,但我认为这样可行:
([A-Za-z0-9]{5}-){6}[A-Za-z0-9]
答案 2 :(得分:1)
对于您的示例,通常将C
替换为您想要的字符类:
^(C{5}-){6}C$
^([a-z]{5}-){6}[a-z]$ # Just letter, use case insensitive modifier
^([a-z0-9]{5}-){6}[a-z0-9]$ # Letters and digits..
答案 3 :(得分:0)
试试这个:
^(C{5}-){6}C$
^
和$
分别表示字符串的开头和结尾,并确保没有输入其他字符。