PowerShell: How to Extract Substring Before Specific Character


You can use the following basic syntax to extract the substring before a specific character in PowerShell:

$findchar = $my_string.IndexOf(" ")
$substring_before = $my_string.Substring(0, $findchar)

This particular example extracts the substring stored in the variable named $my_string that occurs before the space.

The resulting substring is stored in a variable named $substring_before.

The following example shows how to use this syntax in practice.

Example: How to Extract Substring Before Specific Character in PowerShell

Suppose that we have the following string that is used as an employee ID:

  • 00343HAAD Matthew

And suppose that we would like to extract only the text before the space in the employee ID to get the following substring:

  • 00343HAAD

We can use the following syntax to do so:

$my_string = "00343HAAD Matthew"
$findchar = $my_string.IndexOf(" ")
$substring_before = $my_string.Substring(0, $findchar)

The following screenshot shows how to use this syntax in practice:

PowerShell extract substring before specific character

Notice that this returns 00343HAAD, which represents the entire substring that occurs before the space.

How This Syntax Works

Recall the syntax that we used to extract the substring before the space:

$findchar = $my_string.IndexOf(" ")
$substring_before = $my_string.Substring(0, $findchar)

First, we used the IndexOf() method to find the position of the space in the string.

In the string 00343HAAD Matthew this returns a position of 9.

Next, we used the Substring() method to return the substring between the positions 0 and 9 in the original string.

This substring turned out to be 00343HAAD.

Note: To return a substring that occurs before a different delimiter, simply specify that delimiter in the IndexOf() method.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply