Reputation: 1691
I want to validate an expression. I could able to achieve 90% however I am failing on one condition. How we can add an expression to make sure that particular character after few number of character should be an alphabet and next if any should be a number.
Eg: [A-Z1-9]{1,30}?[A-Z]{0,1}$[1-9]{0,1}
The pattern can have max 32 characters and last 2 characters are optional
If the character exceeds 30 it should starts with an alphabet [A-Z]
and it should occur only once {0,1}
And the 32nd character should be a number [1-9]
and it should occur only once and should present if 31st char exists
Could you help me please ?
Upvotes: 3
Views: 1754
Reputation: 2812
Your text is unclear. If 31st character exists is the 32nd character optional or required?
[A-Z1-9]{0,30}?(?:[A-Z]|[A-Z][1-9])?
This one allows 30 characters, 31 characters or 32 characters.
[A-Z1-9]{0,30}?(?:[A-Z][1-9])?
This one allows 30 characters or 32 characters (i.e. if 31st is present then 32nd is required).
Upvotes: 1
Reputation: 69339
Try the following pattern. This matches 1-29 "normal" characters, or exactly 30 characters with your optional suffix.
// Matches 29 chars Matches 30 chars plus suffix
// | |
// ----------------------------------------------
// | || |
String pattern = "([A-Z\\d]{1,29})|([A-Z\\d]{30}([A-Z]\\d){0,1})";
// ^^^^^^^^ ^^^^^^^^
The underlined parts (^^^^
) should be adjusted to describe the set of characters you allow in the first 30 characters.
Note: I've used 0-9
as valid numbers, which is more normal. If you really need 1-9
you can adjust the code.
Upvotes: 4