Java Regular Expression to validate last two characters

java, regex

Solution

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.

Problem

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 ?

Original source