TeamA1
TeamA1

Reputation: 193

How to make regular expression with only 3 characters and 3 digits?

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

Answers (6)

Renjith
Renjith

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}
  1. check for combination

  2. check for only digit or not

  3. check for only alphabets.

Upvotes: 0

Jonny 5
Jonny 5

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].

test on regex101

Upvotes: 8

zx81
zx81

Reputation: 41838

Here you go:

^(?=(?:[a-z]*\d){3})(?=(?:\d*[a-z]){3})\w{6}$

http://regex101.com/r/hO5jY9

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?

  1. This is a classic password-validation-style regex.
  2. The two lookaheads check that we have at least three digits and at least three letters
  3. After these assertions, we are free to match any 6 characters with \w{6} until the end of the string

The 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

thefourtheye
thefourtheye

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

stema
stema

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}$

See it on Regexr

This will do what you want.

  1. \w is not what you want, it also includes \d and the underscore "_".

  2. (?=.*\d.*\d.*\d) is a positive lookahead assertion to check the condition of three digits in the string.

  3. (?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z]) is a positive lookahead assertion to check the condition of three letters in the string.

  4. .{6} checks for a length of 6 overall

Upvotes: 7

James Hibbard
James Hibbard

Reputation: 17755

If you just want to match any six-character combination of digits and "word characters" use:

/^[\d\w]{6}$/

Upvotes: 0

Related Questions