Reputation: 2910
I need help on regular expression on the condition (4) below:
Not sure how to do this. Any help is appreciated, with the sample and some explanations.
Upvotes: 5
Views: 6954
Reputation: 545578
So basically:
[a-z]
.[a-z0-9]
, several times. 1)[._-]
, followed by[a-z0-9]
[a-z0-9]
(implied in the above).Which yields:
^[a-z][a-z0-9]*([._-][a-z0-9]+){0,3}$
But beware that this may result in user names with only one character.
1) (posted by @codeka)
Upvotes: 7
Reputation:
Well, because I feel like being ... me. One Regex does not need to rule them all -- and for one of the Nine, see nqueens. (However, in this case there are some nice answers already; I'm just pointing out a slightly different approach.)
function valid(n) {
return (n.length > 3
&& n.match(/^[a-z]/i)
&& n.match(/[a-z0-9]$/i)
&& !n.match(/[._-]{2}/)
}
Now imagine that you only allow one ., _ or - total (perhaps I misread the initial requirements shrug); that's easy to add (and visualize):
&& n.replace(/[^._-]/g, "").length <= 1
And before anyone says "that's less efficient", go profile it in the intended usage. Also note, I didn't give up using regular expressions entirely, they are a wonderful thing.
Upvotes: 1
Reputation: 383736
You can try this:
^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$
This uses lookaheads to enforce that username must have between 5 and 10 characters (?=.{5,10}$)
, and that none of the 3 special characters appear twice in a row (?!.*[._-]{2})
, but overall they can appear any number of times (Konrad interprets it differently, in that the 3 special characters can appear up to 3 times).
Here's a test harness in Java:
String[] test = {
"abc",
"abcde",
"acd_e",
"_abcd",
"abcd_",
"a__bc",
"a_.bc",
"a_b.c-d",
"a_b_c_d_e",
"this-is-too-long",
};
for (String s : test) {
System.out.format("%s %B %n", s,
s.matches("^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$")
);
}
This prints:
abc FALSE
abcde TRUE
acd_e TRUE
_abcd FALSE
abcd_ FALSE
a__bc FALSE
a_.bc FALSE
a_b.c-d TRUE
a_b_c_d_e TRUE
this-is-too-long FALSE
Upvotes: 9
Reputation: 3969
try that:
^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$
1) ^[a-zA-Z]: beginning
2) (([._-][a-zA-Z0-9])|[a-zA-Z0-9])*: any number of either alphanum, or special char followed by alphanum
3) [a-z0-9]$
Upvotes: 5