How to group expressions to be matched as one?

Viewed 35

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:

  • AB001
  • aB999
  • Hm000
  • en789
  • rv005-ab

These should be invalid:

  • ab (because only letters)
  • abcfr (because too much letters)
  • 158 (because only numbers)
  • 78532 (because too much numbers)
  • 123ab (because all letters should come before numbers, optionalValue exepted)
  • a1b23 (because letters and numbers are mixed)

What am i doing wrong ? (please be gentle this is my first post ever on stackoverflow)

2 Answers

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 string

Regex demo

Or using word boundaries \b instead of anchors

\b[a-zA-Z]{2,3}[0-9]{3}(?:-[a-zA-Z]+)?\b

Regex demo

I have corrected your regex below. Please give it a try.

([A-Za-z]{1,2})([0-9]{3})(-\w*)?

Demo

Related