This is a regex I will use in a PowerShell script to match if any of the below "Write-*" match unless it is in a comment (comment starts with # and does not need to be at the beginning of a line) Write-Host Write-Output Write-Verbose Write-Error Write-Debug Write-Warning
I suppose I should also take into consideration aliases, but I can cross that bridge once I understand how to properly structure this regex
Regex so far:
(?i)^(?!.*#).*Write-(Host|Output|Verbose|Error|Debug|Warning).*$
The below match as expected.
Write-Host
Write-Verbose
if ($True){write-Warning}
The below does not match as expected.
#Write-Host
# Write-Host
# "command is commented out" Write-Output
I expect the below to match but it does not. What should I change in the regex to make the below match successfully too?
Write-output #Comment after command
write-warning #Write-Warning
CodePudding user response:
Instead of a negative lookahead assertion, you can use a character class to exclude #
s from appearing before Write-
:
(?i)^[^#]*Write-(Host|Output|Verbose|Error|Debug|Warning).*$
The green highlight shows what is in capture group 1.