none
String Split by Length RRS feed

  • Question

  • Anyone have a quick way to split strings by length? I'm working with base64 strings and trying to get them into 4 character blocks so I can do smaller scale conversion to decimal (some characters are invalid and require some analysis so a simple conversion is not possible). The string length is variable, so static substring commands won't do. Currently, I'm dumping into a char array and joining the values back together when $array.length % 4 = 0. Any help would be much appreciated.

    Example:

    $string=12341234123412341234

    Desiredoutput:

    @(1234,1234,1234,1234)

    Wednesday, June 7, 2017 10:57 PM

Answers

  • Powershell
    '1234567890ABCDEFGHIJ' -split '(\w{4})' | ? {$_}


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    • Proposed as answer by jrv Thursday, June 8, 2017 12:56 AM
    • Marked as answer by TDWanders Thursday, June 8, 2017 5:56 AM
    Wednesday, June 7, 2017 11:59 PM

All replies

  • Powershell
    '1234567890ABCDEFGHIJ' -split '(\w{4})' | ? {$_}


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    • Proposed as answer by jrv Thursday, June 8, 2017 12:56 AM
    • Marked as answer by TDWanders Thursday, June 8, 2017 5:56 AM
    Wednesday, June 7, 2017 11:59 PM
  • Thanks Grüße, works great. I thought I had already attempted using regex with split from .split(), but can't find it in my command history. Probably an idea I forgot to test when I was working through possible solutions.
    Thursday, June 8, 2017 5:58 AM
  • Glad it was helpful.  

    BTW: "Grüße" is German and means something like "Best regards"   ;-)


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    Thursday, June 8, 2017 6:07 AM
  • LOL, new to the forum and definitely don't know German (if that was a question). 
    Thursday, June 8, 2017 2:07 PM