开发者

RegEx getting script & parameters .. almost there

I'm trying to parse a Powershell script for its functions and parameters. I am almost there, byt I am having troubles with newlines. The expression parses test2 to test6 fine but with test1 I cannot get it to work.

I could of course specify my clients do not use the first syntax, but there must be a way. Can someone point me in the right direction? FWIW: I'm using this in C#.

The regex I'm using is: "function (\w*)\s*\{\s*param\((.*)\)\s*}"

content testfile.ps1:

function test1    {
  param([string]$parm1, [int]$parm2,
    [bool]$parm3)}


function test2
{
    param([int]$parm2, [bool]$parm3)

}

function test3
{    param(blabla3)}

function test4 { param(blabla4) }
function test5 {param(blabla开发者_如何学Python5)}
function test6{param(blabla6)}

Thanks, Alex


Because you didn't show you code I'm guessing that you didn't tell the Regex object that newlines were allowed. You can do this with the RegexOptions.Singleline option. This changes the behavior of the . expression to allow it to match against newline (\n). However, if you do your expression could match more than you want. Regular expressions are greedy and this (.*) will consume up to the last parenthesis in the file. You might want to try something like:

function (\w*)\s*\{\s*param\(([^)]*)\)\s*}


Is your regex in single line or multi-line match mode?

I think:

"^function (\w*)\s*\{\s*param\((.*)\)\s*}$"

might work in multi-line mode. I dont have Expresso open available right now to test it.


function (\w*).*?\{.*?[A-Za-z]+\((.*?)\).*?}

Enable multiline matching on "." as mentioned and use this. I tested against http://www.myregextester.com/ and it seemed to work.

I've replaced your \s* with .*?. This matches any character, non-greedy, until the next specified sequence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜