Arshellan
Arshellan

Reputation: 55

How to group expressions to be matched as one?

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

Answers (2)

The fourth bird
The fourth bird

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 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

Upvotes: 4

Liju
Liju

Reputation: 2313

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

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

Demo

Upvotes: 0

Related Questions