procedure TForm2.Button1Click(Sender: TObject);
var Lines, Params: TStringList;
i, j: integer;
Executable: string;
CurSwitch, CurSwitchValue: string;
begin
Lines := TStringList.Create();
// some test command lines
Lines.Add('C:\MyWork\MyExecutable.exe');
Lines.Add('C:\Delphi\MyThingy.exe -a c:\readme.txt');
Lines.Add('C:\Programs\Stuff\Program.exe -s normal -a c:\readme.txt');
Lines.Add('C:\Programs\Stuff\Program.exe -s normal -q -a c:\readme.txt');
// dummy to hold params
Params := TStringList.Create();
for i := 0 to Lines.Count - 1 do
begin
// go through all the test lines
Params.Clear();
Parse(Lines[i], Executable, Params);
// so now we have the executable in Executable
// and all params in the Params stringlist, in a name value type of way
// so you can go:
for j := 0 to Params.Count - 1 do
begin
CurSwitch := Params.Names[j];
CurSwitchValue := Params.ValueFromIndex[j];
// now you have the switch of argument j in CurSwitch, and it's value in CurSwitchValue
if CurSwitch = '-a' then
DoSwitchA(CurSwitchValue);
end;
end;
Params.Free();
Lines.Free();
end;
procedure TForm2.Parse(Line: string; out Executable: string; Params: TStringList);
const SEPERATOR = ' -';
var p: integer;
CurParam: string;
begin
// first find the executable (which is all untill the first ' -');
p := Pos(SEPERATOR, Line);
if p = 0 then
begin
// no arguments found, just return the executable
Executable := Trim(Line);
exit;
end
else
begin
// copy the executable from the line
Executable := Trim(Copy(Line, 1, p - 1));
// and remove it from the source
Delete(Line, 1, p);
end;
// since we now have the executable, search for more arguments, all seperated by ' -'
while (Trim(Line) <> '') and (p <> 0) do
begin
// search for the next seperator
p := PosEx(SEPERATOR, Line, Length(SEPERATOR));
// if we didn't find a 2nd seperator, copy all that's left
if p = 0 then
p := Length(Line);
CurParam := Trim(Copy(Line, 1, p));
Delete(Line, 1, p);
// now we have a param in CurParam, split up the switch and the value and put it
// in the stringlist, this piece of code assumes that the switch is only 1 char long
Params.Add(Trim(Copy(CurParam, 1, 2)) + '=' + Trim(Copy(CurParam, 3, Length(CurParam))));
Params.CommaText;
end;
end;
SplitTS.text := StringReplace(Line, Delimeter, #13#10, [rfReplaceAll]);
Where Delimiter is ' -'
=====================
Although it won't give the name/value pairs, this would seem to quickly parse the line.
Executable := Trim(SplitTS[0]);
SplitTS[0].Delete;
Params := SplitTS;
Each switch/value pair would need to be parsed as already mentioned.
<Root_Element>
<Program Name="C:\MyWork\MyExecutable.exe"/>
<Program Name="C:\Delphi\MyThingy.exe">
<Switch Name="a" Value="c:\readme.txt"/>
</Program>
<Program Name="C:\Programs\Stuff\Program.exe">
<Switch Name="s" Value="normal"/>
<Switch Name="a" Value="c:\readme.txt"/>
</Program>
</Root_Element>