I’m trying to build a regular expression for validating a SWTOR character name.
It needs to follow these rules:
- Start with an uppercase letter
- End with a lowercase letter
- Only the first letter is uppercase, all other letters are lowercase
- 3-15 characters in length
- Can contain up to two apostrophes (‘)
- Can contain up to one dash (-)
- Apostrophes can’t be next to each other or a dash (No “Jo”e” or “Jo’-e”)
- Entire name can only contain letters, apostrophes, and dashes.
So far, this is what I have which satisfies the first 4 rules and part of 5 and 6 and 8:
^([A-Z])([a-z'-]){1,13}([a-z])$
But my knowledge of regex is quite limited and I got stumped trying to figure out how to add the additional conditions around apostrophes and dashes.
Update: Added rule #8 for clarification per richardtallent’s feedback/answer.
Ok, let’s take these in turn:
First letter is uppercase:
Negative lookahead assertion, ensure there aren’t two dashes, any uppercase letters, two consecutive apostrophes, a dash and apostrophe together, or three apostrophes anywhere ahead:
Then we need to actually match the middle characters, there must be between 1 and 13 of them:
Finally, end with matching the lowercase letter:
For the full expression, just combine the pieces:
I’m assuming the .NET dialect of Regex since you didn’t specify.
Update: Added rule 8 and the part I missed from rule 7.