RegEX string to specific lengths

RegEX string to specific lengths

Hey all I am terrible at RegEX so I am posting this question in hopes that a RegEX Guru will easily know and share the answer.
I have the following string types:
508815 AYBK1619RAUEZP
AWBZ4222TYBE1207CWSWER
DEFAULT EP1 O25R60

And I am needing it in this format (split):
508815 AYBK1619 RAU EZP
AWBZ4222 TYBE1207 CWS WER
DEFAULT EP1 O25 R60

So:
xxxxxxxx xxxxxxxx xxx xxx

First 8 characters in string
Next 8 characters in string
Next 3 characters in string
Last 3 characters in string

I can do the Mid(x,x) and all to do that but I figured that using RegEX would be quicker and cleaner looking code.
Any help would be great! Thanks!

Solutions/Answers:

Solution 1:

You can use the following regex to get what you need:

^(\w{0,8})\s*(\w+)\s*(\w{3})(\w{3})$

This regex will:

  1. Match the 0 to 8 word characters from the beginning of the string
  2. Followed by 0 or more spaces
  3. Followed by 1 or more word characters
  4. Followed by 0 or more spaces
  5. Followed by 3 word characters
  6. Followed by 3 word characters
  7. End of string

Word characters (\w) are any alphanumeric character, plus the underscore character. If you strictly want only capital letters for instance, you can replace \w with a character class of A-Z (any letter in the range A-Z), using [A-Z]

See example

Solution 2:

If your desire is to actually use regex to split at those positions, you could use the following:

Dim s As String = "508815  AYBK1619RAUEZP"
Dim m() As String = Regex.Split(s, "(?<=^.{8})|(?<=^.{16})|(?<=^.{19})")
Console.WriteLine(String.Join(" ", m)) '=> "508815   AYBK1619 RAU EZP"

You could also just match the substrings at those positions instead of splitting …

Dim s As String = "AWBZ4222TYBE1207CWSWER"
Dim m As Match = Regex.Match(s, "^(.{8})(.{8})(.{3})(.{3})$")
If m.Success Then
   Console.WriteLine(
          String.Join(" ", 
                      m.Groups(1).Value,
                      m.Groups(2).Value,
                      m.Groups(3).Value,
                      m.Groups(4).Value
                     ))
End If

'**Output => "AWBZ4222 TYBE1207 CWS WER"

Related:  VIM: Insert text using regex

References