A username is a unique identifier chosen by a user to identify themselves on a computer system or online service. It is often used in combination with a password to authenticate a user and grant them access to certain features or information. Usernames are typically used on websites, email services, and other online platforms, as well as on local computer systems that use a login system or website. In this article let’s understand how we can create a regex for username and how regex can be matched for a valid username.
Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.
Structure of Strong Username
- It should have atleast 6 characters and maximum of 30 characters
- It should have atleast 1 alphabet
- It can optionally have underscore
_
- No special characters are allowed
Regex for checking if username is valid
Regular Expression-
For a username containing minimum 6-30 characters, with at least 1 letter-
/^\w{6,30}$/gm
Test string examples for the above regex-
Input String | Match Output |
---|---|
$%^&abcabcabc | does not match |
rocky_star | matches |
34212 | does not match |
iamyou | matches |
Here is a detailed explanation of the above regex-
/^\w{6,30}$/gm
^ asserts position at start of a line
\w matches any word character (equivalent to [a-zA-Z0-9_])
{6,30} matches the previous token between 6 and 30 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Hope this article was useful to match valid username regex pattern. In conclusion, a username serves as a unique digital identity, crucial for accessing online services and systems. Creating a strong username that adheres to specific criteria ensures security and proper functionality. Utilizing regular expressions (regex) to validate and match valid usernames is a powerful technique. Regex aids in text manipulation, pattern identification, and user input validation, playing a vital role in programming, text editing, and various tools.