Regex pattern for username validation

Viewed 308

I am trying to put together a regex pattern to validate usernames in our account creation PS script. The format of our usernames are FirstName.LastName. We do accept hyphens,apostrophes and numbers also but only as follows:

Firstname - letters only, hyphens, apostrophes also accepted.

LastName - alphanumeric accepted, hyphens and apostrophes also accepted.

The below regex seems to work but it doesn't work for if the username begins or ends with an apostrophe/hyphen as they are valid characters.

"^[a-zA-Z]+-*'*[a-zA-Z]+\.[a-zA-Z]+-*'*[0-9a-zA-Z]+$"

How would i amend the above to also ensure the string doesn't match if it begins or ends with an apostrophe or hyphen? i'd also like to limit hyphens and apostrophes to only 1 consecutive (E.g. "sh-aun" and not "sha--un, "sh'aun" and not "sh''aun") in both the firstname part and lastname part.

Any help would be much appreciated. Thanks in advance.

2 Answers

You are using both hyphen and apostrophe in the first character set, and it is allowing it to match the words starting with these characters. The following one should work

^[a-zA-Z]+-?'?[a-zA-Z]+\.[0-9a-zA-Z]+-?'?[a-zA-Z]+$

? allows the engine to match zero or one occurence of the preceding token

  • PowerShell's regex-matching is case-insensitive by default, so [a-z] is sufficient to match both lowercase and uppercase letters.

  • [a-z] only matches ASCII (non-accented) letters; to also allow accented letters, use \p{L} instead.

To allow multiple - and ' per first and last name (but neither at the start nor at the end, and not consecutively):

"^[a-z]+(?:[-'][a-z]+)*\.[a-z]+(?:[-'][a-z0-9]+)*$"
  • For an explanation of this regex and interactive experimentation with it, see this regex101.com page.

  • Example:

    # -> $true
    "shaun.o'brien-Thompson" -match "^[a-z]+(?:[-'][a-z]+)*\.[a-z]+(?:[-'][a-z0-9]+)*$"
    

To allow just one (internal) - or ', replace the * with ?:

"^[a-z]+(?:[-'][a-z]+)?\.[a-z]+(?:[-'][a-z0-9]+)?$"
Related