Search code examples
regexposix

Regular Expression for a Persons Initials


I have a requirement to validate a persons Initials against the following rules:

  1. Must Start with an Alpha (A-Z)
  2. Must End with an Alpha (A-Z)
  3. Alpha Characters Must be separated by either a Space or Hyphen

This is as far as I have got:

^[[:alpha:]]([[:alpha:]]|([[:blank:]-])[[:alpha:]])*([[:blank:]-][:alpha:]|[:alpha:])?$

It does 1 and 2 (and allows for spaces and hyphens) but does not ensure that alpha characters are separated by either a space or hyphen i.e AD evaluates to true.

Thanks for any help. I am pretty new to Regular Expressions so any help is appreciated.


Solution

  • ^([A-Z][ -])*[A-Z]$
    -                     start
     -         --         any number of times
      -----                 a capital letter
           ----             followed by exactly one separator (space or hyphen)
                 -----    followed by a final (and possibly initial) capital letter