Powershell从字符串中删除文本

Powershell从字符串中删除文本,powershell,Powershell,我有一根绳子 [Test:ABC.Test(6)]moretextgoesher[(null)]-一只红狐跳过了栅栏 并希望修剪字符串以仅显示 一只红狐跳过了栅栏 最好的办法是什么。我肯定我会使用子字符串和IndexOfs,但也许一些正则表达式可以做到这一点?使用子字符串可以做到: PS> $str = '[Test: ABC.Test (6)] MORETEXTGOESHERE [(null)] <(null)> - ' +` 'A red fox ju

我有一根绳子

[Test:ABC.Test(6)]moretextgoesher[(null)]-一只红狐跳过了栅栏

并希望修剪字符串以仅显示

一只红狐跳过了栅栏


最好的办法是什么。我肯定我会使用子字符串和IndexOfs,但也许一些正则表达式可以做到这一点?

使用子字符串可以做到:

PS> $str = '[Test: ABC.Test (6)] MORETEXTGOESHERE [(null)] <(null)> - ' +`
           'A red fox jumped the fence'
PS> $str.Substring($str.LastIndexOf('-')+2)
A red fox jumped the fence
如果逐行处理,我喜欢这种方法:

PS> if ($str -match '-\s*([^-]*)$') { $matches[1] }
A red fox jumped the fence
使用更真实的字符串:

PS> $str = '2010-09-09 07:15:31,749 [ABC: TEST.TEST (3)] ABB MYCLASS.TEST ' +`
           '[(null)] <(null)> - MessageId: ' +`
           '46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED'
PS> if ($str -match '- MessageId:\s*(.*)$') { $matches[1] }
46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED

使用子字符串可以执行以下操作:

PS> $str = '[Test: ABC.Test (6)] MORETEXTGOESHERE [(null)] <(null)> - ' +`
           'A red fox jumped the fence'
PS> $str.Substring($str.LastIndexOf('-')+2)
A red fox jumped the fence
如果逐行处理,我喜欢这种方法:

PS> if ($str -match '-\s*([^-]*)$') { $matches[1] }
A red fox jumped the fence
使用更真实的字符串:

PS> $str = '2010-09-09 07:15:31,749 [ABC: TEST.TEST (3)] ABB MYCLASS.TEST ' +`
           '[(null)] <(null)> - MessageId: ' +`
           '46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED'
PS> if ($str -match '- MessageId:\s*(.*)$') { $matches[1] }
46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED

如果您的字符串具有固定模式…即。您感兴趣的文本总是在后面,并且文本中没有“>”,那么在“>”上拆分输入行并返回数组的第二个元素如何。

如果字符串具有固定模式…即。您感兴趣的文本总是在后面,并且文本中没有“>”,那么在“>”上拆分输入行并返回数组的第二个元素如何。

Hmm。。也许我没有描绘完整的画面,对不起。这里有一个更真实的例子2010-09-09 07:15:31749[ABC:TEST.TEST(3)]ABB MYCLASS.TEST[(null)]-MessageId:46b8fd3c-9ce8-4699-9d1b-91f31bb5c62 CREATEDDo您想从MessageId提取到最后的所有内容,还是想省略“CREATED”?嗯。。也许我没有描绘完整的画面,对不起。这里有一个更真实的例子2010-09-09 07:15:31749[ABC:TEST.TEST(3)]ABB MYCLASS.TEST[(null)]-MessageId:46b8fd3c-9ce8-4699-9d1b-91f31bb5c62 CREATEDDo您想提取从MessageId到最后的所有内容,还是想省略“CREATED”?