Reputation: 193
I have tried the below regex for match here http://rubular.com/ but it matches only 3 characters or 3 digits at a time.
^((\d{3})|(\w{3}))$
I need result like this:
123eee
4r43fs
Upvotes: 8
Views: 17262
Reputation: 216
Hi we can do this in two ways.
If you need IE7 support " ? " expression will give some issues .So you can check like below.
[\d\w]{6} && ![\d]{6} && ![\w]{6}
check for combination
check for only digit or not
check for only alphabets.
Upvotes: 0
Reputation: 12389
One lookahead should be enough to check, if there are exactly 3 digits:
^(?=\D*(?:\d\D*){3}$)[^\W_]{6}$
Used [^\W_]
as shorthand for [A-Za-z0-9]
.
Upvotes: 8
Reputation: 41838
Here you go:
^(?=(?:[a-z]*\d){3})(?=(?:\d*[a-z]){3})\w{6}$
If there are at least three digits, at least three letters, and at most six characters, the string has to match.
How does this work?
\w{6}
until the end of the stringThe lookaheads
Let's break down the first lookahead: (?=(?:[a-z]*\d){3})
It asserts that three times ({3}
), at this position in the string, which is the start of the string as asserted by ^
, we are able to match any number of letters, followed by a single digit. This mean there must be at least three digits.
Upvotes: 9
Reputation: 239473
function checker(data) {
var splitted = data.split(/\d/);
if (splitted.length === 4) {
return splitted.join("").split(/[a-zA-Z]/).length === 4;
}
return false;
}
console.assert(checker("123eee") === true);
console.assert(checker("4r43fs") === true);
console.assert(checker("abcd12") === false);
console.assert(checker("4444ab") === false);
console.assert(checker("ab1c") === false);
console.assert(checker("444_ab") === false);
Upvotes: 2
Reputation: 92986
If you want to use regex it is quite complicated:
^(?=.*\d.*\d.*\d)(?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z]).{6}$
This will do what you want.
\w
is not what you want, it also includes \d
and the underscore "_".
(?=.*\d.*\d.*\d)
is a positive lookahead assertion to check the condition of three digits in the string.
(?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z])
is a positive lookahead assertion to check the condition of three letters in the string.
.{6}
checks for a length of 6 overall
Upvotes: 7
Reputation: 17755
If you just want to match any six-character combination of digits and "word characters" use:
/^[\d\w]{6}$/
Upvotes: 0