2019-06-13
PowerShell to remove text from a string
源自: stackoverflow
问题

What is the best way to remove all text in a string after a specific character? In my case "=" and after another character in my case a ,, but keep the text between?

Sample input

=keep this,

答案
1

Another way to do this is with operator -replace.

$teststring = "test=keep this, but not this."

$teststring -replace ".*=" -replace ",.*"

.*= means any number of characters up to and including an equals sign.

,.* means a comma followed by any number of characters.

Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.

PowerShell to remove text from a string
查看原网页