Home > OS >  PowerShell's replace operator fails to find this RegEx pattern
PowerShell's replace operator fails to find this RegEx pattern

Time:07-25

For example if I have a text called $MarkdownText whose content is this :


This is not in a code block

Command 1
Command 2
Command 3

This is not in a code block

Command 4
Command 5
Command 6

I am trying to parse any strings in the text that are wrapped in pairs of three backticks, like so:

This is not in a code block

[code]
Command 1
Command 2
Command 3
[/code]

This is not in a code block
[code]
Command 4
Command 5
Command 6
[/code]

My code in PowerShell so far is:

$MarkdownText = Get-Content -Path "./codebloack.md" -Raw

$MarkdownText -Replace '```\n(.*?)\n```', '[code]$1[/code]' | Set-Content -Path .\Output.txt

When I run both lines, I don't get any errors at all Powershell creates the Output.txt file but nothing is changed, Its exactly the same as the input file.

My RegEx matches just fine on RegE101, HERE is the link.

I am sooo close to completing this project, just stuck on this last tag

PS: I know there are libraries that will do this sort of thing in a much better way but I am using this to learn PowerShell and Regular Expressions.

CodePudding user response:

You need to use

(?s)```\r?\n(.*?)\r?\n```

See this regex demo. Details:

  • (?s) - a RegexOptions.Singleline option
  • ``` - three backticks
  • \r?\n - a CRLF or LF line ending
  • (.*?) - Group 1: any zero or more chars as few as possible
  • \r?\n - a CRLF or LF line ending
  • ``` - three backticks
  • Related