Moving strings for multiple instances of substrings - freepascal or delphi

Platform: Lazarus 1.1, FreePascal 2.7.1, Win 7 32-bit.

I have a string value as follows:

FileName[12345][45678][6789].jpg 

By default (suppose this behavior is set to 0 by default), my program currently pulls the last set of numbers from the last pair of square brackets to the farthest right of the file name, i.e. 6789. It does this using this code:

 if chkbxOverrideUniqueID.Checked then IDOverrideValue := StrToInt(edtToggleValue.Text); // User is happy to find the right most unique ID if not chkbxOverrideUniqueID.Checked then LastSquareBracket := RPos(']', strFileName); PreceedingSquareBracket := RPosEx('[', strFileName, LastSquareBracket) + 1; strFileID := AnsiMidStr(strFileName, PreceedingSquareBracket, LastSquareBracket - PreceedingSquareBracket) else // User doesn't want to find the rightmost ID. // and now I am stuck! 

However, I have now added the ability for the user to specify behavior other than the default. for example, if they enter “1,” it means “look up the first identifier from the farthest valid identifier”. for example [45678], because [6789] is the default behavior of 0, remember. If they go in 2, I want to find [12345].

My question is: how do I adapt the code above to achieve this, please?

+4
source share
1 answer

The following code will only return a numeric value between brackets:

 uses StrUtils; function GetNumber(const Text: string; Index: Integer): string; var I: Integer; OpenPos: Integer; ClosePos: Integer; begin Result := ''; ClosePos := Length(Text) + 1; for I := 0 to Index do begin ClosePos := RPosEx(']', Text, ClosePos - 1); if ClosePos = 0 then Exit; end; OpenPos := RPosEx('[', Text, ClosePos - 1); if OpenPos <> 0 then Result := Copy(Text, OpenPos + 1, ClosePos - OpenPos - 1); end; 

If you want this value to include these brackets, replace the last line with the following:

 Result := Copy(Text, OpenPos, ClosePos - OpenPos + 1); 
+6
source

All Articles