PowerShell: How to Remove All Text Before Specific Character


Often you may want to remove all text before a specific character in a string in PowerShell.

You can use the following methods to do so:

Method 1: Remove All Text Before Specific Character

$my_string -replace '^[^Employee]*', ''

This particular example removes all text from the string variable named $my_string that occurs before the pattern “Employee” in the string.

Method 2: Remove All Text Before and Including Specific Character

$my_string -replace '^.*Employee'

This particular example removes all text from the string variable named $my_string that occurs before and including the pattern “Employee” in the string.

Here is what the following commands do:

  • ^: Indicates the beginning of a string
  • *: Indicates any amount of characters

The following example shows how to use each of these methods in practice.

Example 1: Remove All Text Before Specific Character in PowerShell

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

  • A003EmployeeGreg

And suppose that we would like to remove all of the text that occurs before “Employee” in the string so that we are left with the following:

  • EmployeeGreg

We can use the following syntax to do so:

$my_string = "A003EmployeeGreg"
$my_string -replace '^[^Employee]*', ''

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

PowerShell remove text before character

Notice that this returns EmployeeGreg, which represents the original string with all text before “Employee” removed.

Example 2: Remove All Text Before and Including Specific Character in PowerShell

Once again, suppose that we have the following string that is used as an employee ID:

  • A003EmployeeGreg

And suppose that we would like to remove all of the text that occurs before and including “Employee” in the string so that we are left with the following:

  • Greg

We can use the following syntax to do so:

$my_string = "A003EmployeeGreg"
$my_string -replace '^.*Employee'

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

PowerShell remove text before and including character

Notice that this returns Greg, which represents the original string with all text before and including “Employee” removed.

Note: The -replace operator is not case-sensitive. If you would like to use a case-sensitive operator, you can use -creplace instead.

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 Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply