0

Need to replace strings after pattern matching. Using powershell v4. Log line is -

"08:02:37.961" level="DEBUG" "Outbound message: [32056][Sent: HTTP]" threadId="40744"

Need to remove level and threadId completely. Expected line is -

"08:02:37.961" "Outbound message: [32056][Sent: HTTP]"

Have already tried following but did not work -

$line.Replace('level="\w+"','') 

AND

$line.Replace('threadId="\d+"','') 

Help needed with correct replace command. Thanks.

2 Answers 2

5

Try this regex:

$line = "08:02:37.961" level="DEBUG" "Outbound message: [32056][Sent: HTTP]" threadId="40744"
$line -replace '(\s*(level|threadId)="[^"]+")'

Result:

"08:02:37.961" "Outbound message: [32056][Sent: HTTP]"

Regex details:

(                    # Match the regular expression below and capture its match into backreference number 1
   \s                # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
      *              # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   (                 # Match the regular expression below and capture its match into backreference number 2
                     # Match either the regular expression below (attempting the next alternative only if this one fails)
         level       # Match the characters “level” literally
      |              # Or match regular expression number 2 below (the entire group fails if this one fails to match)
         threadId    # Match the characters “threadId” literally
   )
   ="                # Match the characters “="” literally
   [^"]              # Match any character that is NOT a “"”
      +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   "                 # Match the character “"” literally
)
Sign up to request clarification or add additional context in comments.

Comments

2

.replace() doesn't use regex. https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.8 -replace does.

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.