我想使用正则表达式验证 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/