Reputation: 1191
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
ABC
Using 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.
Upvotes: 6
Views: 8142
Reputation: 383756
Here's a quick regular expression lesson:
a
matches exactly one a
a+
matches one or more a
in a rowab
matches a
followed by b
ab+
matches a
followed by one or more b
in a row(ab)+
matches one or more of a
followed by b
So in this case, something like this should work:
^([A-Z][.])+$
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".
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).
Upvotes: 5
Reputation: 4749
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]\.)+$
Upvotes: 7
Reputation: 298938
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
Upvotes: 3