近日在和朋友讨论 maskmatch 时偶得2个不错的算法。
函数1 只支持'*','?'模糊匹配。速度比采用递归算法的快近2倍,比tmask方法快很多。
函数2 完全支持正规表达式。速度于之前的相同。(不会正规表达式的朋友慎用)
// ===========================
// funtion 1
// ===========================
// check if the string can match the wildcard. it can be used for unicode strings as well!
// c: 2004-07-24 | m: 2004-07-24
function maskmatch(const apattern, asource: string): boolean;
var
stringptr, patternptr: pchar;
stringres, patternres: pchar;
begin
result := false;
stringptr := pchar(uppercase(asource));
patternptr := pchar(uppercase(apattern));
stringres := nil;
patternres := nil;
repeat
repeat // ohne vorangegangenes "*"
case patternptr^ of
#0 : begin
result := stringptr^ = #0;
if result or (stringres = nil) or (patternres = nil) then exit;
stringptr := stringres;
patternptr := patternres;
break;
end;
'*': begin
inc(patternptr);
patternres := patternptr;
break;
end;
'?': begin
if stringptr^ = #0 then exit;
inc(stringptr);
inc(patternptr);
end;
else begin
if stringptr^ = #0 then exit;
if stringptr^ <> patternptr^ then
begin
if (stringres = nil) or (patternres = nil) then exit;
stringptr := stringres;
patternptr := patternres;
break;
end else
begin
inc(stringptr);
inc(patternptr);
end;
end;
end;
until false;
repeat // mit vorangegangenem "*"
case patternptr^ of
#0 : begin
result := true;
exit;
end;
'*': begin
inc(patternptr);
patternres := patternptr;
end;
'?': begin
if stringptr^ = #0 then exit;
inc(stringptr);
inc(patternptr);
end;
else begin
repeat
if stringptr^ = #0 then exit;
if stringptr^ = patternptr^ then break;
inc(stringptr);
until false;
inc(stringptr);
stringres := stringptr;
inc(patternptr);
break;