Reputation: 441
I'm writing an app in PHP that needs to test a field for a proper voucher code. The voucher entry can be in one of three patterns. I'm no good at expressions, so was hoping for a little help from some of the experts here.
The three patterns are: 1000150000 (any 10 digits) 12345678 (any 8 digits) 3JFK-TAB-CDEFG (First spot a number, the rest alpha. With or without hyphens)
I'm thinking, because the three voucher entries are so different, it might have to be done in three different IF statements.
Thanks for any/all help!!! Rick
Upvotes: 0
Views: 105
Reputation: 89557
You can use this:
/^[0-9](?:[0-9]{7}(?:[0-9]{2})?|[A-Z]*(?>-[A-Z]+)*)$/
The main interests of this pattern are:
9ABCD-EFGH-
(that finishs with an hyphen)Upvotes: 0
Reputation: 4095
You could do this:
(^\d{10}$|^\d{8}$|^\d[A-Za-z-]+$)
Working regex example:
Upvotes: 4
Reputation: 3904
(\d{10})?(\d{8})?(\d[a-zA-Z-]+)?
This creates three optional groups, 1-3, that will capture any 10 digits (group 1), any 8 digits (group 2), or a number followed by alpha characters, with or without hyphens (group 3).
Here is a link to the expression on regex101.
Upvotes: 0
Reputation: 44386
Or you could use alternation. That is, write the three regexs and string them together with the | sign meaning "Match one of this".
So
/[^...$]|\d|Z$/
(I.e. three characters or contains a number or ends with Z.)
Upvotes: -1