SharpShade
SharpShade

Reputation: 2163

Regex match the main expression only if certain length is given

I am trying to match license plates which can only have a maximum of 8 characters in total. The regex should match both styles M-MB 304 or M MB 304 and ignore whitespaces. Additionally it should match partial plates (only M or M-).

So all words and digits except - should end up between 1 and 8 characters.

This is what I've come up with, it matches the correct groups, but I cannot get it to work with a length limit. I tried a positive lookahead at the start which should match all allowed signs, yet it doesn't work. It always matches plates with 9 or more characters and doesn't some with less.

^(?=(?:\w|\d|[^-]){1,8})(?<city>[A-ZÖÜÄ]{1,3})(?:-(?<letters>[A-ZÖÜÄ]{1,2}) ?(?<numbers>[1-9]{1}([0-9]{1,3})*))?$

These should match or not:

// Valid
R
R-
RM
RM-
RMG
RMG-
R-MA 233
R-MA 2333
R MB 2333

// Invalid
RMG-MA2033
MGD-MB 2332

Upvotes: 0

Views: 47

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

You might write the pattern as:

^(?=\w(?:[ -]?\w){0,7}-?$)(?<city>[A-ZÖÜÄ]{1,3})(?:[- ](?<letters>[A-ZÖÜÄ]{1,2}) ?(?<numbers>[1-9](?:[0-9]{1,3})*)?)?-?$

Explanation

  • ^ Start of string
  • (?=\w(?:[ -]?\w){0,7}-?$) Assert 8 word characters to the right with optional space or - in between and optional - at the end
  • (?<city>[A-ZÖÜÄ]{1,3}) Capture group city, match 1-3 times any of the listed characters
  • (?: Non capture group
    • [- ] Match either a space or -
    • (?<letters>[A-ZÖÜÄ]{1,2}) ? Capture group letters, match 1 or 2 times any of the listed characters and an optional space
    • (?<numbers>[1-9](?:[0-9]{1,3})*)? Optional capture group numbers
  • )? Close non capture group and make it optional
  • -? Match optional -
  • $ End of string

Regex demo

Upvotes: 1

Related Questions