views:

98

answers:

1

i Have an arguments like the one below which i pass to powershell script

-arg1 -abc -def -arg2 -ghi -jkl -arg3 -123 -234

Now i need to extract three strings without any whitespace

string 1: "-abc -def" 

string 2: "-ghi -jkl"

string 3: "-123 -234"

i figured this expression could do it. But this doesnt seem to work.

$args -match '-arg1(?'arg1'.*?) -arg3(?'arg3'.*?) -arg3(?'arg3'.*)'. 

THis should return $matches['arg1'] etc. So whats wrong in above expression. Why do i get an error as shown below

runScript.ps1 -arg1 -abc -def -arg2 -ghi -jkl -arg3 -123 -234

Unexpected token 'arg1'.*?) -arg2
(?'arg2'.*?) -arg3 (?'arg3'.*)'' in
expression or statement. At
G:\powershell\tools\powershell\runTest.ps1:1
char:71
+ $args -match '-arg1 (?'arg1'.*?) -arg2 (?'arg2'.*?) -arg3 (?'arg3'.*)' <<<<
    + CategoryInfo          : ParserError: (arg1'.*?) -arg2...g3
(?'arg3'.*)':String) [],
ParseException
    + FullyQualifiedErrorId : UnexpectedToken

and also the second question is how do i make arg1 or arg2 or arg3 optional?

The argument to script can be

-arg2 -def -ghi.

I'll take some default values for arg(1|2|3) that is not mentioned.

Thanks

A: 

seems like the stack overflow syntax highlighter already spoils it for you: you're double-using the ' character; for named groups, and for the entire string.

I can't try as i dont have PS on this box, but what about:

$args -match '-arg1(?<arg1>.*?) -arg2(?<arg2>.*?) -arg3(?<arg3>.*)'

?

additionally, i would replace the spaces with \s+, so that multiple whitespace characters between the parameters are also allowed.

skrebbel
thanks .when i do that, no matches return. echo $matches[0] gives an error saying that "cannot index to a null array"