Marcio Barroso
Marcio Barroso

Reputation: 783

Work with conditional groups in REGEX

I'm trying to match a pattern, but I could not fix my REGEX to work well.

I have the text:

REG1QA

And my regex is bellow:

([A-Z]{3})+([1-3]{1})+([A-Z]{1})+((A|B|C)|(D|E|F)|(G|H|I))

The rules is: If my 4th charactere is 1 my last charactere must be A, B or C If my 4th charactere is 2 my last charactere must be D, E or F If my 4th charactere is 3 my last charactere must be G, H or I

How can I fix my REGEX to accept this rule?

tks

Upvotes: 1

Views: 61

Answers (3)

rekire
rekire

Reputation: 47945

Try this here:

^[A-Z]{3}(1[A-Z]*[ABC]|2[A-Z]*[DEF]|3[A-Z]*[GHI])$

I'm not sure if char 5 can be A-Z too but expected this in my example. So you have a common beginning with a switch for 1-3 and its rules.

Upvotes: 1

Ωmega
Ωmega

Reputation: 43663

Use regex pattern ^.{3}(?:1.*[A-C]|2.*[D-F]|3.*[G-I])$

Upvotes: 1

Vyacheslav Voronchuk
Vyacheslav Voronchuk

Reputation: 2463

[A-Z]{3}((1.*?[A-C]$)|(2.*?[D-F]$)|(3.*?[G-I]$))

Upvotes: 0

Related Questions