tags:

views:

50

answers:

2

I have a string

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

and would like to trim the string to only show

A red fox jumped the fence

What is the best way to go about it. I'm sure I'll manage with SubStrings and IndexOfs but perhaps some regex expression could do the trick?

+1  A: 

Using substring you can do this:

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

That's a bit brittle if processing a line with no - characters. Here's a regex that would work:

PS> $str | Select-String '-\s*([^-]*)$' | Foreach{$_.Matches[0].Groups[1].Value}
A red fox jumped the fence

And if processing line by line, I like this approach:

PS> if ($str -match '-\s*([^-]*)$') { $matches[1] }
A red fox jumped the fence

And with the more realistic string:

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

or if you don't want CREATED in the output:

PS> if ($str -match '- MessageId:\s*(.*?)\s+CREATED\s*$') { $matches[1] }
46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62
Keith Hill
Hmm.. perhaps I didnt paint the full picture, sorry.
Henno
Here's a more real life example2010-09-09 07:15:31,749 [ABC: TEST.TEST (3)] ABB MYCLASS.TEST [(null)] <(null)> - MessageId: 46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED
Henno
Do you want to extract everything from MessageId to the end or do you want to leave out 'CREATED'?
Keith Hill
+1  A: 

If your string has a fixed pattern...i.e. the text you are interested is always after <(null)>, and there is no ">" in the text, then how about splitting the input line on ">" and getting the 2nd element of the array returned.

shivashis