Validate the given string which includes the alphanumeric of the length either 6 or 7 (includes space or hyphen only once)
the input string length is either 6 or 7 characters if includes a hyphen or space its length should be 7. Only one space or Hyphen is allowed as a max
Note: the Hyphen or Space is any place in the string and in the below example given few
ex:
A12B3C -> Valid
ACB1234 -> Valid
123H67J -> Valid
ABC-123 -> Valid
ANV 123 -> Valid
ABV-12345 -> Not Valid
ABC 1234 -> Not Valid
ABC-12 -> NOT Valid
ABC 12 -> Not Valid
ABV--35 -> Not Valid
AV- 345 -> Not Valid
AV- 124 -> Not Valid
AV- 124 -> Not Valid
AV-12 5 -> Not Valid
AV-12 5 -> Not Valid
Regex: ^(?![^0-9A-Z]*([0-9A-Z])(?:[^0-9A-Z]*\1) [^0-9A-Z]*$)(?=.{7}$)[0-9A-Z] (?:[- ][0-9A-Z] )?$
failed the cases like ANV123 as its expected 7 characters
CodePudding user response:
Here's the solution as discussed in the comments of your main post.
^[A-Z0-9]{6,7}$|(?=^.{7}$)^[A-Z0-9] [- ]?[A-Z0-9] $
When asking a question, please be sure to outline all of your requirements. Its very hard for people to give a correct solution to questions that they don't know the full context of.
CodePudding user response:
From looking at your examples, it sounds like what you want is:
- Three alphabetic characters
[A-Z]{3}
- An optional space or hyphen
[ -]?
- Three or four digits
[0-9]{3,4}
Which looks like this, with the beginning and end of string anchors.
^[A-Z]{3}[ -]?[0-9]{3,4}$