Mahesh B
Mahesh B

Reputation: 15

Combine Regular expression Based on Condition in Java

Following could be accepted formats,

(CCC|CC|CCN)/(NNNN-NNNNNNNN)
OR 
(CCC|CC|CCN)/NN/(NN-NNNNN)

Where C represents character [A-Z] and N represents Number [0-9]

I manage to create 2 regular expression to match both the conditions,

^[A-Z]{2}[A-Z|0-9]{0,1}/\d{4,8}$
OR
^[A-Z]{2}[A-Z|0-9]{0,1}/\d{2}/\d{2,5}$

Is it possible to merge them in a single regex based on condition on / (i.e. number of forward slash)?

Sample Valid examples could be :-


MAT/1234
XP/1234
XW1/12345678

XU/12/34
KLY/12/34567
RT1/23/45678

Upvotes: 0

Views: 201

Answers (3)

Quinn
Quinn

Reputation: 4504

UPDATE To merge your following two patterns into one:

^[A-Z]{2}[A-Z|0-9]{0,1}/\d{4,8}$
OR
^[A-Z]{2}[A-Z|0-9]{0,1}/\d{2}/\d{2,5}$

You could try:

^[A-Z]{2}[A-Z|0-9]{0,1}/\d{2}(?:\d{2,6}|/\d{2,5})$

REGEX DEMO

Upvotes: 0

user2705585
user2705585

Reputation:

Based on your current format I came up with this regex.

Well not yet sure if OP is looking for format 1111-11111111 or numbers with length of 4 to 8. So I will give solution for both cases which might come in handy to someone in future.

For format: (NNNN-NNNNNNNN) OR NN/(NN-NNNNN)

Regex: ^([A-Z]{2}[A-Z0-9]?)\/((\d{4}-\d{8})|(\d{2}\/\d{2}-\d{5}))$

Regex101 Demo


For length of numbers in range 4 to 8 and 2 to 5

Regex: ^([A-Z]{2}[A-Z0-9]?\/)(\d{4,8}|\d{2}\/\d{2,5})$

Regex101 Demo

Upvotes: 1

Saleem
Saleem

Reputation: 8978

Well, I got little bit longer regex:

(?im)^([a-z]{2}[\\da-z]?)/(\\d{4}\\-\\d{8}|\\d{2}/\\d{2}\\-\\d{5})$

See demo at regex101

MATCHES:

AA2/2222-22222222
AAA/2222-22222222
AA/2222-22222222

AA2/22/22-22222
AA/22/22-22222
AAB/22/22-22222

BUT NOT

AA2A/2222-22222222A
AAA/2222-222A22222
AA/2222-222222223

2A2/22/22-222222
3AA/22/22-22222
1AB/22/22-22222

Upvotes: 0

Related Questions