我正在努力让名字首字母的正则表达式验证起作用。
我有以下代码:
// S.P. of Sp.A.
string voorletters = "S.P.aAa"; // This should be invalid
string regexPattern = "^([A-Z]{1}[.]|[A-Z]{1}[a-z]{1,}[.])*";
var isMatch = Regex.IsMatch(voorletters, regexPattern);
以下示例应该无效,但确实匹配,因此会通过。 http://regexhero.net/tester/?id=439e7c6e-ce74-4b5a-ac60-d8abeee69675
如何强制量词(*)进行验证?
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试这种模式:
"^([A-Z]{1}[.]|[A-Z]{1}[a-z]{1,}[.]??)*$"
最后的$是必需的,因为在你的用例中,匹配的部分实际上只是“S.P.”。 “??”在第二个点后面是可选的,取决于你在实践中想要什么 - 应该“S.P.Aa”工作与否?
答案 2 :(得分:0)
尝试使用:
^([A-Z][a-z]*\.)+$
<强>解释强>
The regular expression:
(?-imsx:^([A-Z][a-z]*\.)+$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (1 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
[A-Z] any character of: 'A' to 'Z'
----------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
)+ end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------