Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming

How to determine if a string matches a pattern

By Zarko Gajic, About.com

Sometimes we need to know if a string matches a pattern, which is a string with wildcards ( for example ? and * ) .

~~~~~~~~~~~~~~~~~~~~~~~~~
{
Usage:
if IsLike('About Delphi', 'Abo?? Delp*') then
   ShowMessage('A match!') ;
}

uses SysUtils;

function IsLike(AString, Pattern: string): boolean;
var
   j, n, n1, n2: integer ;
   p1, p2: pchar ;
label
   match, nomatch;
begin
   AString := UpperCase(AString) ;
   Pattern := UpperCase(Pattern) ;
   n1 := Length(AString) ;
   n2 := Length(Pattern) ;
   if n1 < n2 then n := n1 else n := n2;
   p1 := pchar(AString) ;
   p2 := pchar(Pattern) ;
   for j := 1 to n do begin
     if p2^ = '*' then goto match;
     if (p2^ <> '?') and ( p2^ <> p1^ ) then goto nomatch;
     inc(p1) ; inc(p2) ;
   end;
   if n1 > n2 then begin
nomatch:
     Result := False;
     exit;
   end else if n1 < n2 then begin
     for j := n1 + 1 to n2 do begin
       if not ( p2^ in ['*','?'] ) then goto nomatch ;
       inc(p2) ;
     end;
   end;
match:
   Result := True
end;

~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Get Printer Handle By Name
« How to install an INF file using Delphi

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2003 Delphi Tips
  7. How to determine if a string matches a pattern

©2009 About.com, a part of The New York Times Company.

All rights reserved.