I generate a 6 characters long random number. It can be all numeric, alphabets and alphanumeric. I have to validate this string on basis of provided regular expression. For example:
If string is numeric [0-9]
, then it should not contain all zeroes.
If string is alphabetic [a-zA-Z]
, then last character cannot be X
or x
. And string cannot start with SVC
or svc
.
If string is alphanumeric [0-9a-zA-Z]
, then it cannot contain all zeroes 0
. And string cannot start with tripple zeroes 000
and cannot end with x
or X
.
I need regular expressions for these that can be used with Java Matcher
.
This should work:
/^((?!.{7,})[0-9]*[1-9]+[0-9]*|(?!(SVC|svc))[a-zA-Z]{5}[a-wy-zA-WY-Z]|(?!(000|.{7,}))[0-9a-zA-Z]*([a-zA-Z][0-9]|[0-9][a-zA-Z])+[0-9a-zA-Z]*[a-wy-zA-WY-Z])$/gm
I cannot explain this regex, as it is too long and just a repetitive application of the same concepts over and over. However, given the following input, it matches only the first five lines:
002000
jfkasd
002dfd
sVcabc
abc65i
000000
00012c
0123ax
SVCabx
svcabc
abc65x
abc65X
Here's the original attempt I proposed, which does not satisfy all the condition of the OP, but it is accompained by an explanation:
/^((?!.{7,})[0-9]*[1-9]+[0-9]*|[a-zA-Z]{5}[a-wy-zA-WY-Z]|(?!000)[0-9a-zA-Z]{6})$/gm
Explanation (which could read on the linked page itself):
- We have three alternatives that have to match the whole line:
^(…|…|…)$
; - The 2nd alernative is easy: five letters followed by one letter which is not
x
orX
,[a-zA-Z]{5}[a-wy-zA-WY-Z]
([^xX]
would match numers too or anything else). - The 3rd alternative is slightly more complex: six letters or digits, which is not preceded by
000
; this uses a negative lookahead, and it works because of the anchor^
(if you remove that, it breaks). - The 1st alternative is similar: zero or more digits, followed by one or more non-0 digits, followed by zero or more digits; all not starting by 7 or more characters.