Reputation: 29468
Hi I need a regular expression which is accepting the following strings:
[A-Z]-[A-Z]{3-5}[0-9]{2-4}
for example X-ABC123 or Y-AB1234
The problem now is that the total length of the string on the right side of the hyphen must always be 5 chars in length. Is there a chance to check that with regular expressions only?
Upvotes: 0
Views: 230
Reputation: 26930
Just add this after the hyphen :
/(?=[A-Z\d]{5}$)/
Resulting in :
/^[A-Z]-(?=[A-Z\d]{5}$)[A-Z]{3,5}[0-9]{2,4}/
This assumes that your input strings are the strings you posted.
X-ABC123 -> fails
Y-AB1234 -> fails
A-ABD12 -> matches
A-ABV111 -> fails
If the string is part of another string you can replace the $ anchor with \s|$ for example.
Upvotes: 1
Reputation: 17445
I think it's definitely possible, from a language theory point of view. Just group it and add the constraint :
I just need to know which language is specifying the regex but something like this :
[A-Z]-(^[A-Z][A-Z0-9]4)
I had the feeling you wanted the right part to start with one char for sure, then either chars or numbers
Upvotes: 0
Reputation: 92976
First the problems in your regex
The quantifier is {3,5}
and not {3-5}
(this would match literally "{3-5}")
You want 3 to 5 letters and 2 to 4 digits and in total 5 letters and digits ==> the only valid combination is then 3 letters followed by 2 digits.
In general you can use a positive lookahead for this
^[A-Z]-(?=.{5}$)[A-Z]{3,5}[0-9]{2,4}$
See it here on Regexr
The (?=.{5}$)
part is just looking, if there are from its position to the end ($
) 5 characters.
But as said before, if the 3-5 and 2-4 and overall 5 is valid you can just do
^[A-Z]-[A-Z]{3}[0-9]{2}$
Upvotes: 0