To learn Regex, I was solving some problems to train and study. And this is the problem, i know it might not be the best way to do with Regex, and my Regex is a mess, but i liked the challenge.
Problem:
- The names needs to be Title Case;
- There are exceptions for some lowercase words inside;
- And some Names, e.g.: McDonald, MacDuff, D'Estoile
- Names with
'and-are accepted, and sometimes they are o'Brien, O'brien, O'Brien, O' Brien or 'Ehu Kali. - No whitespaces on the beggining and end of Name;
- No more than one space between each Name of Full Name;
- A
.is accepted if not alone, e.g.: Dan . Ferdnand (isn't accepted) and Dan G. Ferdnand (is accepted) - Numbers and symbols are not accepted
- However, Roman numbers are accepted and aren't Title Case, e.g.: Elizabeth II
- Some names can be alone, e.g.: Akihito (Prince of Japan)
- Some special characters common in some countries are accepted, e.g.: Valeh ßlÿsgÿroğlu, Lażżru Role, Alaksiej Taraškievič
Regex
The code is
^(?![ ])(?!.*(?:\d|[ ]{2}|[!$%^&*()_+|~=`\{\}\[\]:";<>?,\/]))(?:(?:e|da|do|das|dos|de|d'|la|las|el|los|l'|al|of|the|el-|al-|di|van|der|op|den|ter|te|ten|ben|ibn)\s*?|(?:[A-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð'][^\s]*\s*?)(?!.*[ ]$))+$
And the Regex101 with a validation list
References
What i tried so far was based on these:
- regular expression for first and last name
- Regular Expression to disallow two consecutive white spaces in the middle of a string
- A regex to test if all words are title-case
- How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
- Use Regex to Split Numbered List array into Numbered List Multiline
Not working
I did this Regex and don't know how to make a way for it to not recognize the cases below, that are matching:
- CAPITAL LETTER
- AlTeRnAtE LeTtEr
And those aren't and should:
- Urxan Əbűlhəsənzadə
- İsmət Jafarov
- Şükür Hagverdiyev
- Űmid Abdurrahimov
- Ġerardo Seralta
- Ċikku Paris
Question
Is there a way to optimize this Regex (monster)?
And how do i fix the problems stated before on Not working?
p.s.: The list of names with examples for validation can be found on the link to Regex101.