Search code examples
regexpowershellsubstringcontains

Powershell: How to grab substring of text


I have a field, description which contains text in a predictable format, which looks like either 1 of these 2 options,

DEACTIVATED on Tue Apr 02 2019

or

DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith

I need to grab just the date in each case, Tue Apr 02 2019, while accounting for there either being or not being text after the date.

Example use case

$string = "DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith"
$date   = "Tue Apr 02 2019"

Solution

  • Here's how I got it since I had to account for some potential differences across objects

    $text = "DEACTIVATED on Tue Apr 02 2019 | MANAGER John Smith"
    $start_pos = $text.IndexOf('on')
    
    $substring = $text.substring($start_pos + 3)
    
    if ($text.IndexOf(' | ') -gt -1) {
        $end_pos = $text.indexOf(' | ')
        $substring = $substring.substring(0, $end_pos)
    }