1

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.

1
  • The first of the two condions for the alphanumeric case is redundant. If the number does not start with 000, then it is not all 0s. Commented Feb 21, 2020 at 18:09

1 Answer 1

2

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 or X, [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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Given URL is quite helpful to play with it. Furthermore, SVCabc abc65X should be invalid as well for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.