Home > Software design >  Match overall length on regex groups
Match overall length on regex groups

Time:12-29

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

CodePudding user response:

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

CodePudding user response:

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