0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm.. perhaps I didnt paint the full picture, sorry.
Here's a more real life example 2010-09-09 07:15:31,749 [ABC: TEST.TEST (3)] ABB MYCLASS.TEST [(null)] <(null)> - MessageId: 46b8fd3c-9ce8-4699-9d1b-91f31bfb5c62 CREATED
Do you want to extract everything from MessageId to the end or do you want to leave out 'CREATED'?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.