views:

61

answers:

4

Hey Guys,

I'm having problems creating a regular expression which will fix a valid string.

The string will be in the format: any alpha-numerical character 3 to 5 times, followed by a comma if there are more characters after else its the end of the string

Example Strings: A401,CR56,4U9Y,MO16,ECZGB,A7DC,9LN5,D52PU,UT95,YBPB0,2JWA,AAMW,KVG,6V8W,FWE

TRIR,J107,Q9X,FMFZ,VDAS,557,X7A,DRPB,S97O,8U62B,IN3I,H8MC,WS4C,U04KQ,X05O.

I have tried a few various expressions, but none which seem to match if I have an invalid entry. I know I could explode the string, and loop through the array, but trying to do this in just the one expression as it seems a pretty easy one, but can't quite figure it out.

Exmaple patterns:

echo preg_match("/^([A-Z0-9]{3,5})[,|$]{1,}/",$str);
echo preg_match("/((?<=[^|,])([A-Z0-9]{3,5}){1}(?=[,|$])){1,}/",$str);

and various variations on them, but I can't quite find the winning pattern, all help appreciated.

Cheers, Psy

+2  A: 
/^[A-Z0-9]{3,5}(?:,[A-Z0-9]{3,5})*$/
KennyTM
A little unnecessarily redundant, though.
brianary
+2  A: 
/^([a-z0-9]{3,5},)*[a-z0-9]{3,5}$/
Amarghosh
Funny how minds work differently: I had the same one as KennyTM, yet you choose to put the single `[a-z0-9]{3,5}` to the right (perfectly fine of course). +1 to both of you.
Bart Kiers
A: 

Try:

echo preg_match("/^([A-Z0-9]{3,5}(?:,|$))+/",$str);
brianary
`[,|$]` matches a comma, a vertical bar, or a dollar sign. Grouping is still `(?:...)` unless you work in Perl 6.
KennyTM
No, `[,|$]` matches either `,`, `|` or `$`. It does not match a comma OR the end of the string.
Bart Kiers
Missed that, I was just fixing the improperly nested paren. Didn't even notice the wrong brackets. Fixed.
brianary
A: 

This works for me:

(\w{3,5})[,.]?
Pessimist
This matches `___.`.
KennyTM
"The string will be in the format: any alpha-numerical character 3 to 5 times, followed by a comma if there are more characters after else its the end of the string".Therefore there'll be no ___. There's no reason to overdo it.
Pessimist