JavaScript Regex: Complicated input validation

Posted by ScottSEA on Stack Overflow See other posts from Stack Overflow or by ScottSEA
Published on 2010-06-15T23:27:17Z Indexed on 2010/06/15 23:32 UTC
Read the original article Hit count: 232

Filed under:
|

I'm trying to construct a regex to screen valid part and/or serial numbers in combination, with ranges.

A valid part number is a two alpha, three digit pattern or /[A-z]{2}\d{3}/

i.e. aa123 or ZZ443 etc...

A valid serial number is a five digit pattern, or /\d{5}/

13245 or 31234 and so on.

That part isn't the problem. I want combinations and ranges to be valid as well:

12345, ab123,ab234-ab245, 12346 - 12349 - the ultimate goal. Ranges and/or series of part and/or serial numbers in any combination. Note that spaces are optional when specifying a range or after a comma in a series. Note that a range of part numbers has the same two letter combination on both sides of the range (i.e. ab123 - ab239)

I have been wrestling with this expression for two days now, and haven't come up with anything better than this:

/^(?:[A-z]{2}\d{3}[, ]*)|(?:\d{5}[, ]*)|(?:([A-z]{2})\d{3} ?- ?\4\d{3}[, ]*)|(?:\d{5} ?- ?\d{5}[, ]*)$/

...

My Regex-Fu is weak.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex