Regular expression to validate username
Solution 1
^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
└─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
│ │ │ │ no _ or . at the end
│ │ │ │
│ │ │ allowed characters
│ │ │
│ │ no __ or _. or ._ or .. inside
│ │
│ no _ or . at the beginning
│
username is 8-20 characters long
If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:
^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$
Solution 2
I guess you'd have to use Lookahead expressions here. http://www.regular-expressions.info/lookaround.html
Try
^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
[a-zA-Z0-9]
an alphanumeric THEN (
_(?!\.)
a _ not followed by a . OR
\.(?!_)
a . not followed by a _ OR
[a-zA-Z0-9]
an alphanumeric ) FOR
{6,18}
minimum 6 to maximum 18 times THEN
[a-zA-Z0-9]
an alphanumeric
(First character is alphanum, then 6 to 18 characters, last character is alphanum, 6+2=8, 18+2=20)
Solution 3
As much as I love regular expressions I think there is a limit to what is readable
So I would suggest
new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");
It's longer but it won't need the maintainer to open expresso to understand.
Sure you can comment a long regex but then who ever reads it has to rely on trust.......
Solution 4
A slight modification to Phillip's answer fixes the latest requirement
^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
Solution 5
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
String userName = scan.nextLine();
String regularExpression = "^[[A-Z]|[a-z]][[A-Z]|[a-z]|\\d|[_]]{7,29}$";
if (userName.matches(regularExpression)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
![mohsen dorparasti](https://i.stack.imgur.com/ZLa1M.jpg?s=256&g=1)
Comments
-
mohsen dorparasti almost 2 years
I'm trying to create a regular expression to validate usernames against these criteria:
- Only contains alphanumeric characters, underscore and dot.
- Underscore and dot can't be at the end or
start of a username (e.g
_username
/username_
/.username
/username.
). - Underscore and dot can't be next to each other (e.g
user_.name
). - Underscore or dot can't be used multiple times in a row (e.g
user__name
/user..name
). - Number of characters must be between 8 to 20.
This is what I've done so far; it sounds it enforces all criteria rules but the 5th rule. I don't know how to add the 5th rule to this:
^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$
-
Adam Wolski almost 12 yearsTry:
^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
-
ridgerunner almost 12 yearsYup, this one works. But the
(_|\.)
expression can be streamlined to just[_.]
. -
ridgerunner almost 12 yearsNice one. But you may want to look into using free-spacing mode and embed your comments right in there with the code. +1
-
Ωmega almost 12 years@ridgerunner - I believe this way it is easy to read and port to code.
-
vignesh kumar almost 9 years@Ωmega can we use [\w\.] instead of [a-zA-Z0-9._]
-
Ωmega almost 9 years@vigneshkumar - same meaning, but
[a-zA-Z0-9._]
is easy to read and understand -
Jackson Lenhart over 7 yearsthe
<
in(?<![_.])$
causes a parsing error for me "invalid regular expression" -
Ωmega over 7 years@JacksonLenhart - What regex engine and programming language you use? Please note this question was tagged with
asp.net
tag and while the answer is valid for most of other languages and engines, not all support negative lookahead and lookbehind zero-length assertions. -
Jackson Lenhart over 7 yearsAh yes, I was naive enough to think regex would be the same for all languages. I'm using javascript (es6), no additional regex engine
-
Toto over 4 yearsThis is allowing underscore at the beginning and at the end, which is not wanted.
-
Toto over 4 yearsIt also matches infinite length string that contains only underscore.
-
FrEqDe over 4 years@Toto, I fixed it.
-
Karan Jagtiani over 4 yearsPlease note that this regular expression causes an Angular app to crash on IOS devices, as well as on the Firefox browser.
-
ElRey777 over 4 yearsFor those who will use this in JS: this RegEx works great in Chrome. But it raises an error in Safari, Firefox, Edge, etc.
-
ElRey777 over 4 yearsNice, if somebody need such a RegEx for JS, this is the way. It works in all browsers unlike the most voted answer that's Chrome-only
-
user229044 over 4 yearsFirefox considers this regex to be a syntax error, and produces
SyntaxError: invalid regexp group
. -
Ibrahim Azhar Armar almost 4 yearsThis gives issue in character limit rule, with the given rule of
{6,18}
it accepts min 8 characters whereas it must be accepting 6, If I make it{4,18}
then it will accept 6 characters whereas I have defined 4 -
Eazy about 3 yearsWorks fine, but allows
-
character, I made a little adjustment to it here:^(?=.{4,20}$)(?:[a-zA-Z\d]+(?:[._][a-zA-Z\d])*)+$
which fix it for me, thanks for the code @FrEqDe -
Admin over 2 yearsYour answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-
theProCoder over 2 yearswow, that is very helpful that you specified the sections. thanks so much
-
Richardd over 2 yearsThanks @Ωmega It seems that also run in Flutter for android. I did not tested on ios.