I am looking for regular expression in java that matches the following pattern:
two alternating numeric or alpha values Example: 12121212 or adadadad
numeric or alpha sequences with at least 4 sequential digits Example: cdefgh or 123456
thanks
I am looking for regular expression in java that matches the following pattern:
two alternating numeric or alpha values Example: 12121212 or adadadad
numeric or alpha sequences with at least 4 sequential digits Example: cdefgh or 123456
thanks
Regex's are not designed for parsing these varieties of patterns. However, you might be able to work around this a bit, though it is messy.
The second one could be brute forced for exactly four sequentials fairly easily:
(abcd|bcde|cdef|...|wxyz|0123|1234|...|6789)
But that by no means covers 5 sequentials and higher. That would be nasty.
You could do something similar for the first case, though that's a little more unreasonable because there are 26 letters + 10 digits (I'm assuming you're just doing this for lower case), so if you wanted ANY alternating pairs you would need 36*35 = 1260 possibilities in your regex. Which is a little long. It COULD be done, but it's undesireable.
Your example could of course be parsed as follows:
(12|ab)+
Which is reasonable. But if you're looking for the more generic solution for any number/alphabet pairing, you would need to exhaustively generate the list.
In conclusion, your best bet is NOT to use regular expressions. They're not designed to be used for these sorts of searches.
I think a regex is probably the wrong tool for pattern 2. "all numeric" or "all alpha" is easy, but the "sequential" requirement is going to be tough to express. You're probably better off writing a simple loop to check your requirement.
For the first one, if you have a set SIGMA which is your alphabet, you can do:
(SIGMA SIGMA)+
This DOES allow aaaaaa, but I'm not sure if that's allowed...