开发者

Regex to validate initials

开发者 https://www.devze.com 2023-01-03 10:37 出处:网络
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

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.


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 one a
  • a+ matches one or more a in a row
  • ab 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][.])+$

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

0

精彩评论

暂无评论...
验证码 换一张
取 消