RegEx Group by Fixed Length

Viewed 53

Sample input:

19GMC TRNLLBLK
98CHY TK   GRN
02TOYO   4DWHI
21LAND     BLK

To help see what I'm trying to do:

19|GMC |TRN|LL|BLK
98|CHY |TK |  |GRN
02|TOYO|   |4D|WHI
21|LAND|   |  |BLK

Columns:

  1. Always two digits
  2. Always 3 letters followed by a space or 4 letters
  3. Always all spaces, 2 letters followed by a space or 3 letters
  4. Always all spaces or two characters
  5. Always all spaces or three letters

I'm trying to use RegEx to select the non-white space characters within each "column".

The non-white characters would be part of a group (one for each column).

The white characters would be part of a non-selected group.

(?<DIG>\d{2})(?<MKE>\S{3,4})

I can't figure out how to create a non-selected group that figures out how many white spaces to select to prevent going into the "next column".

1 Answers

You can use 5 capture groups:

^(\d{2})([A-Z]{3}[A-Z ])([A-Z]{2}[A-Z ]| +)([A-Z0-9]{2}| +)([A-Z]{3}| +)$

Explanation

  • ^ Start of string
  • (\d{2}) Group 1, match 2 digits
  • ([A-Z]{3}[A-Z ]) Group 2, match 3 chars A-Z and either a char A-Z or a space
  • ([A-Z]{2}[A-Z ]| +) Group 3, match 2 chars A-Z and either a char A-Z or a space OR only spaces
  • ([A-Z0-9]{2}| +) Group 4, match 2 chars A-Z or 0-9 OR match only spaces
  • ([A-Z]{3}| +) Group 5, match 3 chars A-Z OR only spaces
  • $ End of string

See a regex demo.

Related