Reputation: 1
I have a string which looks something like this:
"Comments : @{id=15161772,we are happy with the service,likes=&÷€$:#,hsbdinsjsonsjbdjdjid}"
I would like to get the part "We are happy with the service".
I have tried something like:
$string ="Comments : @{id=15161772,we are happy with the service,likes=&÷€$:#,hsbdinsjsonsjbdjdjid}"
$string.split(",") | foreach {if(($_ -Notlike "*id=*" ) -and ($_ -Notlike "*likes=*")){$_ }}
I get the result as:
We are happy with the service
hsbdinsjsonsjbdjdjid
I wish to only get "we are happy with the service".
Upvotes: 0
Views: 81
Reputation: 68341
Using a regex split:
$string = 'Comments : @{id=15161772,we are happy with the service,likes=&÷€$:#,hsbdinsjsonsjbdjdjid}'
($string -split 'id=\d+,|,likes=')[1]
we are happy with the service
Upvotes: 1
Reputation: 36332
I'll go for the RegEx option...
$string ='Comments : @{id=15161772,we are happy with the service,likes=&÷€$:#,hsbdinsjsonsjbdjdjid}'
$string -replace ".*?=.*?,(.*?),likes=.*", "`$1"
That outputs your desired text, and should return out everything after the first equals sign, and before ,likes=
. If you want to capture it, just assign it to a variable, such as:
$Comment = $string -replace ".*?=.*?,(.*?),likes=.*", "`$1"
Then $Comment
will contain the string we are happy with the service
.
This should be more flexible than splitting on the comma. See examples and more details on how the RegEx works at: https://regex101.com/r/fK1oX6/1
Upvotes: 1
Reputation: 4464
If you can guarantee that the item you are looking for does not contain commas, then you are simply looking at second element in a comma delimitered string.
$string.split(",")[1]
Upvotes: 1