Regex to validate initials
I'm looking for a regex to validate initials. The only format I want it to allow is:
(a capital followed by a period), and that one or more times
Valid examples:
A.
A.B. A.B.C.Invalid examples:
a.
a A A B A B C AB ABCUsing The Regulator and some websites I have found 开发者_如何学运维the following regex, but it only allows exactly one upper (or lower!) case character followed by a period:
^[A-Z][/.]$
Basically I only need to know how to force upper case characters, and how I can repeat the validation to allow more the one occurence of an upper case character followed by a period.
You almost has it right: +
says "one or more occurenses" and it's \.
, not /.
Wrapping it in ()
denotes that it's a group.
^([A-Z]\.)+$
Here's a quick regular expression lesson:
a
matches exactly onea
a+
matches one or morea
in a rowab
matchesa
followed byb
ab+
matchesa
followed by one or moreb
in a row(ab)+
matches one or more ofa
followed byb
So in this case, something like this should work:
^([A-Z][.])+$
References
- regular-expressions.com/Repetition and Grouping
Variations
You can also use something like this:
^(?:[A-Z]\.)+$
The (?:pattern)
is a non-capturing group. The \.
is how you match a literal .
, because otherwise it's a metacharacter that means "(almost) any character".
References
- regular-expressions.info/The Dot Matches (Almost) Any Character
Even more variations
Since you said you're matching initials, you may want to impose some restriction on what is a reasonable number of repetition.
A limited repetition syntax in regex is something like this:
^(?:[A-Z]\.){1,10}$
This will match at least one, but only up to 10 letters and period repetition (see on rubular.com).
the regex you want is this:
^(?:[A-Z]\.)+$
the ?: marks the group as non-captured
case sensitivity is however a flag which is handled differently in every language. but in most implementations it is active by default
精彩评论