How to add dashes to a string

This topic contains 7 replies, has 3 voices, and was last updated by  Nall White 1 week, 6 days ago.

  • Author
    Posts
  • #84995

    Nall White
    Participant

    I'm generating random numbers using get-random. I want to add dashes every 4 numbers. I need some help in how to do this. Thanks.

  • #84998

    Sam Boutros
    Participant

    have you written any code to do that yet? Please post

  • #85003

    Sam Boutros
    Participant
    #region input
    $myInput        = Get-Random
    $SplitEvery     = 4
    $SplitCharacter = '-'
    #endregion
    
    #region process
    $myString = [String]$myInput
    $i = 1
    $myOutput = $myString.ToCharArray() | % { if ($i % $SplitEvery -eq 0) { "$_$SplitCharacter" } else { $_ }; $i++ }
    #endregion
    
    #region Output
    $myOutput = $myOutput -join ''
    #remove trailing SplitCharacter
    if ($myOutput[-1] -eq $SplitCharacter) { $myOutput = $myOutput[0..($myOutput.Length-2)] -join ''}
    $myOutput
    #endregion
    

    If you don't fully comprehend every line above, please ask..

    • #85007

      Nall White
      Participant

      So far my code was "Get-Random -count 24". I played around with split and nothing I did worked. I remembered this website after erased everything. Thanks!!!

  • #85009

    js
    Participant

    How's this? Replace any 4 characters not at the end of the line.

    '12345678911234567890' -replace '(....(?!$))','$1-'
    
    1234-5678-9112-3456-7890
    
    • #85010

      Nall White
      Participant

      That did work. What is going on here '(....(?!$))','$1- ? Where can I get more info? Thanks!!!

    • #85013

      js
      Participant

      .... is any 4 characters, () let's me refer to it later as $1, (?!$) means lookahead and match not, ! the end of the line, $. Maybe plug it into http://regex101.com

    • #85025

      Nall White
      Participant

      Thanks.

You must be logged in to reply to this topic.