Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular Expression to validate last two characters

Tags:

java

regex

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 ?

like image 214
Prasobh.Kollattu Avatar asked Jun 18 '26 07:06

Prasobh.Kollattu


2 Answers

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.

like image 175
Duncan Jones Avatar answered Jun 20 '26 20:06

Duncan Jones


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).

like image 20
RokL Avatar answered Jun 20 '26 22:06

RokL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!