Python Multiline Replace

Viewed 38

I'm trying to get python to run a PowerShell script over Windows RM, because of the encoding I inject the parameters into the top of the file, however this means I need to remove the existing Param function, I've nearly managed to get the regex working but the "Parameter(Mandatory)" section that is sometimes there is messing up my regex, can someone help me fix it please.

I don't want it to match the word Param that might be elsewhere in the script.

......
Param(
    [Parameter(Mandatory)]
    [String]$TaskName,
    [Switch]$Debug = $false
)

# Debug
if ($Debug)

Python 2.7 command:

args = re.sub("Param(\s*\r*\n[^)]+)", "", scriptfile.read(), re.M )

1 Answers

You can use

(?sm)^\s*Param\(.*?\)$

See the regex demo. This pattern assumes the ) right-hand match boundary is at the end of a line and Param inner lines cannot end with a ) char.

Details:

  • (?sm) - re.S and re.M options enabled
  • ^ - line start
  • \s* -zero or more whitespaces
  • Param\( - Param( string
  • .*? - any zero or more chars as few as possible
  • \) - a ) char
  • $ - end of a line

See the Python demo:

import re
test_str = "Param(\n    [Parameter(Mandatory)]\n    [String]$TaskName,\n    [Switch]$Debug = $false\n)\n\n# Debug\nif ($Debug)\n\nParam(...)"
print (re.sub(r"^\s*Param\(.*?\)$", '', test_str, 0, re.M|re.S))

Output is


# Debug
if ($Debug)
Related