Windows – Regular expression not working on Powershell

powershellregexwindows

Background:
I need to match a multiline pattern(?) in a C# source file. The regular expression will be manipulate by Powershell. I have tested and it works on RegexBuddy (with the Dot Matches newline". But when I try to use it via powershell, it does not work.

Regex:

[\s]*(?!\/)\[Role.*?\].*?\(.*?\).*?;

C# Code:

[Role (MethodName ="param")]
void  doSomething(Param1 Param2);

Powershell code:

$FunctionPattern="^[\s]*(?!\/)\[Role.*?\].*?\(.*?\).*?;"
$FunctionMatch =[regex]::matches($Data,$FunctionPattern)
$FunctionMatch | format-table index,length,value -auto

According to this, for Powershell to use multiline, I have to use the contruct (?m) but this does not work

Help and thanks in advance!!
(Opps I cannot use grep/dedicated parsers/ and findstr does not to multiline without a hacl etc hence the need for Powershell)

Best Answer

The "(?m)" modifier applies to PowerShell operators (-match, -replace, etc), but you are using the .NET RegEx class which doesn't use PowerShell modifiers. In that case you can use the Multiline RegexOptions flag:

[regex]::matches($Data, $FunctionPattern, "Multiline")

But I don't think dot (".") ever matches newlines in .Net/PowerShell. You'll need to use "\r\n" to match newlines.

Related Topic