Mega Code Archive

 
Categories / Delphi / Files
 

Wildcard Comparing Files And String Variables !

Title: Wildcard Comparing Files And String Variables ! Question: I Need To Know How Can I Compare Some Strings Using The Known Wildcards *,? ??? Answer: This small parser can compare 2 strings with the use of wildcards in the second parameter. The rules of wildcards are as follows: * Any matching string of characters. ? Any matching character. The function is expecially usefull when implementing disk access routines where you need to sort files by wildcards. That is also why the function is called SameFile(). Unit filespec; interface uses SysUtils; type TWildCard = class public Function SameFile(File1, File2 : string; isCase : boolean) : Boolean; private Function SameName(N1, N2 : string) : Boolean; end; implementation Function TWildCard.SameName(N1,N2:string) : Boolean; Var P1,P2 : Byte; Match : Boolean; Begin P1 := 1; P2 := 1; Match := True; If (Length(N1) = 0) And (Length(N2) = 0) Then Match := True Else If Length(N1) = 0 Then If N2[1] = '*' Then Match := True Else Match := False Else If Length(N2) = 0 Then If N1[1] = '*' Then Match := True Else Match := False; While (Match = True) And (P1 If (N1[P1] = '?') Or (N2[P2] = '?') Then Begin Inc(P1); Inc(P2); End Else If N1[P1] = '*' Then Begin Inc(P1); If P1 Begin While (P2 Inc(P2); If P2 Length(N2) Then Match := False Else Begin P1 := Succ(Length(N1)); P2 := Succ(Length(N2)); End; End Else P2 := Succ(Length(N2)); End Else If N2[P2] = '*' Then Begin Inc(P2); If P2 Begin While (P1 Inc(P1); If P1 Length(N1) Then Match := False Else Begin P1 := Succ(Length(N1)); P2 := Succ(Length(N2)); End; End Else P1 := Succ(Length(N1)); End Else If N1[P1] = N2[P2] Then Begin Inc(P1); Inc(P2); End Else Match := False; If P1 Length(N1) Then Begin While (P2 Inc(P2); If P2 Match := FALSE; End; If P2 Length(N2) Then Begin While (P1 Inc(P1); If P1 Match := False; End; SameName := Match; End; { ---------------------------------------------------------------------------- } Function TWildCard.SameFile(File1,File2 : string; isCase : boolean) : Boolean; Begin if not isCase then begin File1 := Uppercase(File1); File2 := Uppercase(File2); end; SameFile := SameName(File1,File2); End; End. ((( Usage ))) var Wildcard : TWildcard; begin Wildcard := TWildCard.Create; // Function samefile: // File1: String // File2: String with wildcards to compare with // isCase: True if case sensitive if WildCard.SameFile( 'mystring', 'my*', FALSE ) then ;// This statement would return true if WildCard.SameFile( 'mystring', 'str*', FALSE ) then ;// This statement would return false if WildCard.SameFile( 'mystring', 'm?string', FALSE ) then ;// This statement would return true if WildCard.SameFile( 'mystring', 'm?str', FALSE ) then ;// This statement would return false end; Regards....... Ruslan Abu Zant.