Regex is Beautiful
1 min readNov 6, 2022
Recently I was developing a game using Unity. At the start of the game, the player has to input a name. However, I wanted to restrict the player’s name to alphabetic only.
There are many ways to validate user input, but in this case, I decided to give regex a go. Here is the solution.
if (!Regex.IsMatch(userInput.text, "^[a-zA-Z]+$"))
{
userMessage.text = "Invalid Input: only alphabets are allowed";
return;
}
It’s all in this pattern “^[a-zA-Z]+$”, let have a look:
| ^ | assert the beginning of a line |
| [a-zA-Z] | means lower case and upper case are allowed |
| + | means match one or unlimited from the previous token |
| $ | assert the end of a line |
If you want to limit the length of the user to a maximum of 7, replace the + with {1,7}. This simple solution shows how regex is universal, beautiful, and efficient.