PowerShell: How to Extract Substring After Specific Character


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

$findchar = $my_string.IndexOf(" ")
$substring_after = $my_string.Substring($findchar+1)

This particular example extracts the substring after the space in the string variable named $my_string.

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

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

Example: How to Extract Substring After 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 after the space in the employee ID to get the following substring:

  • Matthew

We can use the following syntax to do so:

$my_string = "00343HAAD Matthew"
$findchar = $my_string.IndexOf(" ")
$substring_after = $my_string.Substring($findchar+1)

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

PowerShell extract substring after character

Notice that this returns Matthew, which represents the entire substring that occurs after the space in the string.

How This Syntax Works

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

$findchar = $my_string.IndexOf(" ")
$substring_after = $my_string.Substring($findchar+1)

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 9+1 and the end of the string.

This substring turned out to be Matthew.

Note #1: The first argument in the Substring() method specifies the starting position of the substring to extract. If no second argument is provided, then it’s assumed that the substring to the end of the string should be extracted.

Note #2: To return a substring that occurs after 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