Prakhar Jain
Prakhar Jain

Reputation: 63

Regx for string 2 digits and 10 alphabets irrespective of their position in string

Regular expression in java for a string which can contain 2 digits & 10 alphabets irrespective of their position in String

Examples of string are:

1abcdefghij2
12abcdefghij
abcdefghij12
abcdefg1hij2
ab12cdefghij

Is it possible?

Upvotes: 0

Views: 40

Answers (2)

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

Yes, it's possible.

[12a-j]+ for strings not limited by length and [12a-j]{12} for string exactly 12 characters long.

You can test it here.

Upvotes: 0

user2705585
user2705585

Reputation:

I think the regex you are looking for is like this.

Regex: ^(?=\D*\d\D*\d\D*$)[a-zA-Z0-9]{12}$

Explanation:

  • (?=\D*\d\D*\d\D*$) checks for presence of 2 digits.

  • [a-zA-Z0-9]{12} makes sure that the total length is 12.

  • Since presence of 2 digits is already checked obviously there will be 10 alphabets.

Regex101 Demo

Edit #1: Edited regex on Sebastian Proske's advice from

^(?=.*\d.*\d)[a-z0-9]{12}$ to ^(?=\D*\d\D*\d\D*$)[a-zA-Z0-9]{12}$

Upvotes: 1

Related Questions