Reputation: 63
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
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
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.
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