Simple Question about splitting

Welcome Forums General PowerShell Q&A Simple Question about splitting

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
1 year, 1 month ago.

  • Author
    Posts
  • #79180

    Participant
    Points: 0
    Rank: Member

    Just wrapping my head around splitting text.

    So i know the basics of splitting

    $text = OK – offset: -31 of 60 WARN – Offset is -31 sec (warn/crit at 30/60 sec)
    $text -split"-"
    

    What i would like is to only split on the first instance of OK – offset , not anywhere else.

    Any idea of doing that?

    TIA

  • #79181

    Participant
    Points: 0
    Rank: Member

    Hi Wei-Yen Tan,
    With -split, you can specify a second parameter that identifies the .
    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split?view=powershell-5.1

    So, if you just want to split it into two substrings you can do the following.

    $text = 'OK – offset: -31 of 60 WARN – Offset is -31 sec (warn/crit at 30/60 sec)'
    $text -split "-",2

    Results:

    OK – offset: 
    31 of 60 WARN – Offset is -31 sec (warn/crit at 30/60 sec)

    See how it splits at the first instance of "-" and results in only 2 substrings?

    Now you may ask why it split at the "-" in front of 31 instead of the "–" between OK and offset. This is because the "–" between OK and Offset is not a Hyphen-Minus character, it is what is called an En Dash (unicode character decimal 8211), so it is not matched when the split is looking for Hyphen-Minus (unicode character decimal 45)

  • #79192

    Participant
    Points: 0
    Rank: Member

    Thanks for that Curtis. Works perfectly.

The topic ‘Simple Question about splitting’ is closed to new replies.