Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern for username validation

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.

like image 313
Shauno100 Avatar asked Apr 22 '26 12:04

Shauno100


2 Answers

  • 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]+)?$"
like image 162
mklement0 Avatar answered Apr 25 '26 12:04

mklement0


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

like image 39
kronos Avatar answered Apr 25 '26 11:04

kronos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!