Simple Question about splitting

Tagged: 

This topic contains 2 replies, has 2 voices, and was last updated by  Wei-Yen Tan 2 weeks, 2 days ago.

  • Author
    Posts
  • #79180

    Wei-Yen Tan
    Participant

    Just wrapping my head around splitting text.

    So i know the basics of splitting
    [pre]
    $text = OK – offset: -31 of 60 WARN – Offset is -31 sec (warn/crit at 30/60 sec)
    $text -split"-"
    [/pre]

    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

    Curtis Smith
    Participant

    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

    Wei-Yen Tan
    Participant

    Thanks for that Curtis. Works perfectly.

You must be logged in to reply to this topic.