Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Repeating Pattern separated by comma

Tags:

regex

I have a regular expression of the following:

.regex(/^(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{4})$/)

Must be exactly 4 characters Must contain at least 1 numeric and 1 alpha

Although I rarely do regular expression, this was relatively easy. I now have a new requirement that I have tried to implement, but cannot get right.

New requirement: Be able to have a comma separated list of the same type of input as before. Cannot end with a comma. Each item must be valid per the rules above (4 characters, at least on numeric, at least one alpha)

Valid:  123F,U6Y7,OOO8
Invalid:  Q2R4,
Invalid:  Q2R4,1234
Invalid:  Q2R4,ABCD
Invalid:  Q2R4,N6

I very much appreciate your help! Thanks!

like image 968
user3006614 Avatar asked Jan 07 '14 04:01

user3006614


People also ask

How do you repeat a regular expression?

An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once. An expression followed by '? ' may be repeated zero or one times only.

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What is Colon in regex?

A colon has no special meaning in Regular Expressions, it just matches a literal colon.


1 Answers

Some of the other answers are repeating the lookahead assertions. That's not necessary.

Here's a regular expression that matches a comma-separated sequence of atoms, where each atom is four alphanumeric characters:

^[A-Z0-9]{4}(?:,[A-Z0-9]{4})*$

Of course, that's not quite what you want. You don't want atoms that are all alphabetic. Here's a negative lookahead assertion that prevents matching such an atom anywhere in the text:

(?!.*[A-Z]{4})

And you don't want atoms that are all numeric either:

(?!.*[0-9]{4})

Putting it all together:

^(?!.*[A-Z]{4})(?!.*[0-9]{4})[A-Z0-9]{4}(?:,[A-Z0-9]{4})*$
like image 113
rob mayoff Avatar answered Oct 06 '22 06:10

rob mayoff