kendarr
kendarr

Reputation: 35

In Powershell get all text between 2 characters

I am trying to collect all the text between 2 characters in a log file.

The example log file text is:

Conversation with Boris at 6/30/2017 7:26:35 AM on Server(jabber)
(7:26:41 AM) [email protected]/Server:  I likes cake
This was a Message from Boris to everyone at 2017-06-29 22:35:18.724681 EVE ~~~

I would like to collect all the text between the first bracket and the last tilde.

I have been trying to use REGEX to do this but am not sure of the correct pattern.

Can anyone help?

Upvotes: 1

Views: 4848

Answers (2)

Chetan Kulkarni
Chetan Kulkarni

Reputation: 404

If your requirement is so fixed that first '(' and last '~',I am giving you a easier looking solution without using Regex.Have a look at it

$x='Conversation with Boris at 6/30/2017 7:26:35 AM on Server(jabber)
(7:26:41 AM) [email protected]/Server:  I likes cake
This was a Message from Boris to everyone at 2017-06-29 22:35:18.724681 EVE ~~~'

$x.Substring($x.IndexOf('('),$x.IndexOf('~~~')-$x.IndexOf('(')+3)


 #Output
    (jabber)
    (7:26:41 AM) [email protected]/Server:  I likes cake
    This was a Message from Boris to everyone at 2017-06-29 22:35:18.724681 EVE ~~~

Hope this helps

Upvotes: 2

Mark Wragg
Mark Wragg

Reputation: 23385

Per the comment from wOxxOm, this regex pattern seems to do the trick: '(?s)\(.*?~+'

Here's how you can use it with PowerShell:

$Sample = @"
Conversation with Boris at 6/30/2017 7:26:35 AM on Server(jabber)
(7:26:41 AM) [email protected]/Server:  I likes cake
This was a Message from Boris to everyone at 2017-06-29 22:35:18.724681 EVE ~~~
"@

$Sample -Match '(?s)\(.*?~+' | Out-Null

$Result = $Matches.Values

Here's $Result:

(jabber)
(7:26:41 AM) [email protected]/Server:  I likes cake
This was a Message from Boris to everyone at 2017-06-29 22:35:18.724681 EVE ~~~

Upvotes: 2

Related Questions