Mario
Mario

Reputation: 39

Match overall length on regex groups

I would like to integrate a total length check into the match, unfortunately I only succeed in the length match on the subgroups themselves.

Requirements: It should contain an alphanumeric string which contains letters from A-Z as well as numbers from 0-9 as well as 1 slash or 1 space but only in the middle, capturing is not needed.

^(?:[A-Z0-9]+(?:(?:-| )[A-Z0-9]+)?)$
^(?:[A-Z0-9]+(?:(?:-| )[A-Z0-9]+)?){1,11}$

Upvotes: 0

Views: 515

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

If I understood you right (valid string must contain at least one character from A-Z, 0-9, /, and must not begins or ends wth /, ), you can try

^(?=.*[A-Z].*)(?=.*[0-9].*)(?=.+[\/].+)(?=.+[ ].+).{1,11}$

pattern:

^              - (anchor) start of the string
(?=.*[A-Z].*)  - contains A-Z somewhere
(?=.*[0-9].*)  - contains 0-9 somewhere
(?=.+[\/].+)   - contains /, but in the middle (not first and not last) 
(?=.+[ ].+)    - contains ' ' (space), but in the middle (not first and not last)
.{1,11}        - from 1 to 11 arbitrary characters
$              - (anchor) end of the string

Upvotes: 0

JvdV
JvdV

Reputation: 75840

Does the following do what you are after:

^(?!.{12})[A-Z0-9]+(?:[- ][A-Z0-9]+)?$

See an online demo. The use of the hyphen or space is now optional. Not sure if you want it compulsary, if so:

^(?!.{12})[A-Z0-9]+[- ][A-Z0-9]+$

Upvotes: 1

Related Questions