Jump to content
xisto Community
Sign in to follow this  

[tutorial] Delphi Multi-Parsing Function

Recommended Posts

I've spent a while trying to create parsing function with Delphi. This language is very useful.This tutorial explains how to parse multiple instances of an item in one string. Here is the function (which I am actually very proud of):Code:function TForm1.MultiParse(MainString, BeginString, EndString: string): TStrings;var PosBeginString, PosEndString, i, LastPos: integer; tmpCopy: string; tmpStrings: TStrings;begin tmpStrings := TStringList.Create; LastPos := 0; for i := 1 to LastDelimiter(EndString, MainString) do begin PosBeginString := PosEx(BeginString, MainString, LastPos) + Length(BeginString); PosEndString := PosEx(EndString, MainString, LastPos); tmpCopy := Copy(MainString, PosBeginString, PosEndString - PosBeginString); if Length(Trim(tmpCopy)) <> 0 then tmpStrings.Add(tmpCopy); LastPos := LastPos + PosEndString; end; Result := tmpStrings;end;Notice how the function returns the parsed data using the data type of TStrings, which is essentially an easier to work with version of a string array.The code would be used as follows:Code:Memo1.Lines.AddStrings(MultiParse('The person named Joe is friendly. The person named Bob is friendly.', 'named ', ' is'));The strings 'Bob' and 'Joe' will both be contained in the returnd TStrings data type, and will be added to Memo1, whose primary "lines" property is also of the same data type.Notes:1) Because of its usage of the PosEx function, to use this function "StrUtils" must be included in the uses section of your unit.2) The code doesn't necessarily need to be contained in a function. You can adapt it to place in a procedure.Enjoy.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.