2010-09-09 74 views
0

刪除文本我有一個字符串PowerShell與字符串

[Test: ABC.Test (6)] MORETEXTGOESHERE [(null)] <(null)> - A red fox jumped the fence

,並想修剪字符串,只顯示

A red fox jumped the fence

什麼是去了解它的最佳方式。我相信我會用SubStrings和IndexOfs來管理,但也許有一些正則表達式可以做到這一點。

回答

2

使用子串,你可以這樣做:

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> $str | Select-String '-\s*([^-]*)$' | Foreach{$_.Matches[0].Groups[1].Value} 
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> if ($str -match '- MessageId:\s*(.*?)\s+CREATED\s*$') { $matches[1] } 
46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 
+0

嗯..也許我沒有畫完整的圖片,對不起。 – Henno 2010-09-09 02:57:20

+0

這裏有一個更真實的例子 2010-09-09 07:15:31,749 [ABC:TEST.TEST(3)] ABB MYCLASS.TEST [(null)] <(null)> - MessageId:46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED – Henno 2010-09-09 02:57:38

+0

你想從MessageId中提取所有內容嗎?或者你想省略'CREATED'嗎? – 2010-09-09 04:17:08

1

如果你的字符串有固定的模式......即,你感興趣的文本總是在<(null)>之後,並且在文本中沒有「>」,那麼如何分割「>」上的輸入行並返回數組的第二個元素。