Durga
Durga

Reputation: 15614

regex for one letter and three number

i tried with this RegEX no solution

^([a-zA-Z]{1})([0-9]{3})$

Test Case: Valid

123d

f311

12d3

99A9

Upvotes: 2

Views: 3659

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can use a lookahead to check there's exactly one letter (case insensitive) and digits:

^(?=\d*[a-z]\d*$).{4}$

or 4 characters:

^(?=.{4}$)\d*[a-z]\d*$

If the lookahead isn't available you can use @cmbuckley pattern, but you can also factorize it. An example in ERE:

^([0-9]([0-9]([0-9][a-z]|[a-z][0-9])|[a-z][0-9]{2})|[a-z][0-9]{3})$

As an aside: never use the quantifier {1}, each token without quantifier occurs one time by default.

Upvotes: 0

JDK
JDK

Reputation: 83

Please check below expression as per your requirement

(?=(?:.*\d){3})(?=(?:.*[a-zA-Z]){1})^[a-zA-Z\d]*$

Breakdown:

Look for at least 3 digits:

(?=(?:.*\d){3})

Look for at least 1 letters:

(?=(?:.*[a-zA-Z]){1})

Define what is allowed between the start and end:

^[a-zA-Z\d]*$

you can check example here.

Upvotes: 1

cmbuckley
cmbuckley

Reputation: 42547

If the combination can be in any order, you may need to list the alternatives explicitly, depending on what your regex flavour supports:

^([a-zA-Z]\d{3}|\d[a-zA-Z]\d{2}|\d{2}[a-zA-Z]\d|\d{3}[a-zA-Z])$

Upvotes: 5

Related Questions