user2847098
user2847098

Reputation: 201

Regex to allow a comma seperated list of codes

I have an input form which I need to validate, the list must follow these rules

Valid example data

Invalid example data

I am using http://www.regexr.com and have got as far as this: [A-Z_]_[A-Z],|[0-9],

The problem with this is the last code in each valid data example is not selected so the line does not pass the regex pattern

Upvotes: 2

Views: 663

Answers (2)

Kamehameha
Kamehameha

Reputation: 5488

Try this -

^(?:[A-Z]_[A-Z]*|[0-9]+)(?:,(?:[A-Z]_[A-Z]*|[0-9]+))*$

Demo

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43286

Try this:

^(?:(?:[A-Za-z]_[A-Za-z]*|\d+)(?:,|$))+(?<!,)$

regex101 demo.


Explanation:

^  start of string
(?:  this group matches a single element in the list:
    (?:
        [A-Za-z]  a character
        _         underscore
        [A-Za-z]* any number of characters (including 0)
    | or
        \d+  digits
    )
    (?: followed by either a comma
        ,
    |  or the end of the string
        $
    )
)+  match any number of list elements
(?<!  make sure there's no trailing comma
    ,
)
$  end of string

Upvotes: 1

Related Questions