tags:

views:

121

answers:

6

I've never used regexes in my life and by jove it looks like a deep pool to dive into. Anyway, I need a regex for this pattern (AN is alphanumeric (a-z or 0-9), N is numeric (0-9) and A is alphabetic (a-z)):

AN,AN,AN,AN,AN,N,N,N,N,N,N,AN,AN,AN,A,A

That's five AN's, followed by six N's, followed by three AN's, followed finally by two A's. If it makes a difference, the language I'm using is Java.

+4  A: 

Replace each AN by [a-z0-9], each N by [0-9], and each A by [a-z].

Dave
This is correct (+1), but the regex is horrible (-1). Alex Martelli's regex is a lot more readable.
Chris Lutz
Exactly, he practically had it himself.
Simucal
+7  A: 
[a-z0-9]{5}[0-9]{6}[a-z0-9]{3}[a-z]{2}

should work in most RE dialects for the tasks as you specified it -- most of them will also support abbreviations such as \d (digit) in lieu of [0-9] (but if alphabetics need to be lowercase, as you appear to be requesting, you'll probably need to spell out the a-z parts).

Alex Martelli
I assume you meant [0-9], not [0--9]. Fixed it for you.
Chris Lutz
The OP asked for 5 alphanumerics at the start of the pattern, not {6}.. you should probably update this for correctness. Something like this is closer to what the OP asked for: [a-z0-9]{5}[0-9]{6}[a-z0-9]{3}[a-z]{2}
Scott Ferguson
A: 

Try looking at some simple java regex tutorials such as this

They'll tell you how you form regular expressions and also how to use it in java.

Prashast
+1  A: 

30 seconds in Expresso:

[a-zA-Z0-9]{5}[0-9]{6}[a-zA-Z0-9]{3}[0-9]{2}

Case insensitive, but you can probably define that in Java instead of the regex.

Si
Expresso is great! I highly second the suggestion of this program as a great way to generate and test regexes.
GreenKiwi
+1  A: 

For the example you posted, the following should work fine.

(([A-Za-z\d])*,){5}+(([\d])*,){6}+(([A-Za-z\d])*,){3}+([\d])*,[\d]*

In Java you should be able use it like this:

boolean foundMatch = subjectString.matches("(([A-Za-z\\d])*,){5}+(([\\d])*,){6}+(([A-Za-z\\d])*,){3}+([\\d])*,[\\d]*");

I used, this tool to help in learning RegEx, it also make this really easy. http://www.regexbuddy.com/

Robert Love
A: 

This should match the pattern you request.

[a-z0-9]{5}[0-9]{6}[a-z0-9]{3}[a-z]{2}

In addition, you could add Beginning of String / End of String matches, if your string match should fail if any other chars are in it:

^[a-z0-9]{5}[0-9]{6}[a-z0-9]{3}[a-z]{2}$
Scott Ferguson