-1

This is my string. I want to replace everything that is not between '{' '}'.

    @═strin3http://schemas.microsoft.com/2003/10/Serialization/??║{
  "Content-Type":"application/json",
  "PlanUrl": "https://dev.azure.com/{org}/",
  "ProjectId": "030a1c12-2657-4168-bfcb-27da2d7bfd94",
  "HubName": "build",
  "PlanId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
  "JobId": "a4f1cc8a-0ccb-5e90-36f4-f06f41d0ce59",
  "TimelineId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
  "TaskInstanceId": "fab2c9a5-dd69-59cd-9de4-4a87ae16ee9f",
  "AuthToken": val }╔

So I use -replace and [regex]::Match( $msContent , '\{(.*?)\}') but it seems I am very bad in this.

How can I get this

{
      "Content-Type":"application/json",
      "PlanUrl": "https://dev.azure.com/{org}/",
      "ProjectId": "030a1c12-2657-4168-bfcb-27da2d7bfd94",
      "HubName": "build",
      "PlanId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
      "JobId": "a4f1cc8a-0ccb-5e90-36f4-f06f41d0ce59",
      "TimelineId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
      "TaskInstanceId": "fab2c9a5-dd69-59cd-9de4-4a87ae16ee9f",
      "AuthToken": val }
  • split on the `{`, take the 2nd result, split on `}`, take the 1st result, add the leading `{` back in, and - finally - add the trailing `}` back. [*grin*] – Lee_Dailey Dec 09 '20 at 09:17

1 Answers1

2

Instead of doing a replace to remove everything that is NOT within the brackets, I'd recommend doing the opposite, and capturing everything that is within the brackets:

$string = '    @═strin3http://schemas.microsoft.com/2003/10/Serialization/??║{
  "Content-Type":"application/json",
  "PlanUrl": "https://dev.azure.com/{org}/",
  "ProjectId": "030a1c12-2657-4168-bfcb-27da2d7bfd94",
  "HubName": "build",
  "PlanId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
  "JobId": "a4f1cc8a-0ccb-5e90-36f4-f06f41d0ce59",
  "TimelineId": "4c38913c-30c2-44cb-a3a6-a6c9533d5b73",
  "TaskInstanceId": "fab2c9a5-dd69-59cd-9de4-4a87ae16ee9f",
  "AuthToken": val }╔'
  
$string -Match '(?s){.*}';
$string = $Matches[0]
$string

Explanation:

  • (?s) - Settings for the regex engine, s puts it into dotall mode, which means a . operator also matches new lines.
  • {.*} - Pretty simple, capture everything that is between the two curly brackets, including the brackets
  • -Match - This operator not only returns a True/False if there is a match, but it populates an automatic variable called $Matches[], which contains all of your matches. [0] is the entire matching string. If your regex uses capture groups, then you can find the value of each capture group by iterating through the array.
Chad Baldwin
  • 2,239
  • 18
  • 32
  • When I try your solution, I got this False } So I go in another way $msContent = [System.Text.Encoding]::ASCII.GetString($SBmessage.Content) -replace '(.+?){', "{" -replace '}(.+?)', '}' | ConvertFrom-Json – Kirill Kiselev Dec 09 '20 at 09:48
  • Yeah, I realized I copy pasted the wrong regex string, I fixed it. – Chad Baldwin Dec 09 '20 at 09:49