Understanding the NAME_REGEX in Linux (used for checking usernames)

  • #1
Wrichik Basu
Insights Author
Gold Member
2022 Award
2,032
2,278
I was helping one of my classmates to set up the Ubuntu app on Windows 10 so that he can do Bash programming. While setting the username, he was getting an error due to bad regex, and that prompted me to look up the regex for username on Linux. This regex is stored in /etc/adduser.conf file. The regex is as follows: ^[a-z][-a-z0-9_]*\$

As far as I understand, this pattern wants the username to begin with a lower case letter. Then there can be zero or more characters, chosen from hyphen, lower case letters, digits, and underscore. At the end, the dollar sign is escaped, so there has to be a literal $ sign at the end.

regex101.com says that my interpretation is correct. In fact, user-name does not match the regex, but user-name$ matches.

However, my username is wrichik-basu, i.e., no $-sign at the end. While setting up the Ubuntu app for my classmate, no dollar sign was required either.

Am I wrong somewhere in understanding the regex?
 

Answers and Replies

  • #2
wle
336
158
At the end, the dollar sign is escaped, so there has to be a literal $ sign at the end.
The backslash might not actually end up in the regex, depending on how backslashes are interpreted in string literals.
Code:
$ echo "^[a-z][-a-z0-9_]*$"
^[a-z][-a-z0-9_]*$
$ echo "^[a-z][-a-z0-9_]*\$"
^[a-z][-a-z0-9_]*$
$ echo "^[a-z][-a-z0-9_]*\\$"
^[a-z][-a-z0-9_]*\$
$ echo '^[a-z][-a-z0-9_]*\$'
^[a-z][-a-z0-9_]*\$
 
  • Like
  • Love
Likes Wrichik Basu and Ibix
  • #3
Wrichik Basu
Insights Author
Gold Member
2022 Award
2,032
2,278
The backslash might not actually end up in the regex, depending on how backslashes are interpreted in string literals.
Yes, you are right. Thanks, that explains it. (In fact, I am learning bash programming right now, and should have found that out myself. :doh: )
 

Suggested for: Understanding the NAME_REGEX in Linux (used for checking usernames)

Replies
17
Views
566
  • Last Post
Replies
1
Views
558
  • Last Post
Replies
5
Views
459
  • Last Post
Replies
9
Views
988
Replies
4
Views
414
Replies
3
Views
639
Replies
17
Views
814
Replies
14
Views
1K
Replies
14
Views
2K
Top