PowerShell从字符串中删除文本

Joe*_*Rod 9 string powershell

在特定字符后删除字符串中所有文本的最佳方法是什么?在我的情况下,"="和我的案例中的另一个角色a ,,但保持文本之间?

样本输入

=保持这个,

Ben*_*ard 31

另一种方法是使用operator -replace.

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

$teststring -replace ".*=" -replace ",.*"
Run Code Online (Sandbox Code Playgroud)

.*= 表示任意数量的字符,包括等号.

,.* 表示逗号后跟任意数量的字符.

由于您基本上删除了字符串的这两部分,因此您不必指定用于替换它们的空字符串.您可以使用多个替换,但请记住订单是从左到右.

  • 只是为了使它更加有效,您可以使用管道“或”替换字符串的开头和结尾。管道发生在字符串开头的匹配项与字符串结尾的匹配项之间,这些匹配项将被丢弃(我在行的开头和结尾使用锚点(^,$表示清楚)) $ teststring -replace'^。* = |,。* $'` (2认同)

Adi*_*tan 6

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]
Run Code Online (Sandbox Code Playgroud)

回报

keep this
Run Code Online (Sandbox Code Playgroud)