Reputation: 55
What i am trying to match is like this :
char-char-int-int-int
char-char-char-int-int-int
char-char-int-int-int-optionnalValue (optionalValue being a "-" plus letters after it
My current regep looks like this :
([A-Za-z]{1,2})([1-9]{3})("-"[\w])
In the end, the regexp should match any of these:
These should be invalid:
What am i doing wrong ? (please be gentle this is my first post ever on stackoverflow)
Upvotes: 2
Views: 41
Reputation: 163632
If you use [A-Za-z]{1,2}
then the second example would not match as there a 3 char-char-char
Using \w
would also match numbers and an underscore. If you mean letters like a-zA-Z you can use that in an optional group preceded by a hyphen (?:-[a-zA-Z]+)?
You could use
^[a-zA-Z]{2,3}[0-9]{3}(?:-[a-zA-Z]+)?$
^
Start of string[a-zA-Z]{2,3}
Match 2 or 3 times a char A-Za-z[0-9]{3}
Match 3 digits(?:-[a-zA-Z]+)?
Optionally match a -
and 1 or more chars A-Za-z$
End of stringOr using word boundaries \b
instead of anchors
\b[a-zA-Z]{2,3}[0-9]{3}(?:-[a-zA-Z]+)?\b
Upvotes: 4