procedure TForm1.BitBtn68Click(Sender: TObject); var s1,s2,s3:string; begin s1:='fdsf3 fdw erAAA('; s2:='edAAA)'; s3:='ff AAA)'; if Pos('ff AAA',s3)>0 then ShowMessage('ok'); end;
if Pos('ff AAA',s)>0 then 这只能找一个, 当Pos('fdsf3 fdw erAAA(' ,'AAA')的时候'fdsf3 fdw erAAA('也是可以找出来的,但是不符合预期结果。
按照“ff AAA“进行匹配就可以了
不知道你是要找'空格AAA'还是'AAA',先搞清楚就可以了
看一下AAA前一个字符和后一个字符是不是空格就可以了。
pos('空格AAA','ff AAA')
function getLocation(substr,s:string):integer; var i,len,x:integer; tmp:string; begin Result:=0; len:=length(substr); if len=0 then exit; tmp:=s; x:=0; while length(tmp)>0 do begin i:=pos(substr,tmp); if i>0 then begin if (i=1) then begin if not(tmp[len+1] in['a'..'z','A'..'Z']) then begin Result:=1; exit; end; end else if (not(tmp[i-1] in['a'..'z','A'..'Z']))and(not(tmp[i+len] in['a'..'z','A'..'Z'])) then begin Result:=x+i; exit; end else begin x:=x+i+len-1; tmp:=copy(tmp,i+len,length(tmp)); end; end else exit; end; end;procedure TForm1.Button1Click(Sender: TObject); var i:integer; substr,s:string; begin substr:='AAA'; s:='(dsfsAAA ghtyAAAghfg AAAgfhgfh AAA)fdgfd'; i:=getLocation(substr,s); if i>0 then showmessage('在第 '+inttostr(i)+' 个位置找字符 “'+substr+'"。') else showmessage('字符串中找不到 “'+substr+'"。'); end;
如果“AAA”的前后不能连着数字,就在if (not(tmp[i-1] in['a'..'z','A'..'Z']))and(not(tmp[i+len] in['a'..'z','A'..'Z'])) then 的判断条件里加上 in['0'..'9']的排斥条件。
procedure TForm1.BitBtn68Click(Sender: TObject);
var
s1,s2,s3:string;
begin
s1:='fdsf3 fdw erAAA(';
s2:='edAAA)';
s3:='ff AAA)'; if Pos('ff AAA',s3)>0 then
ShowMessage('ok');
end;
当Pos('fdsf3 fdw erAAA(' ,'AAA')的时候'fdsf3 fdw erAAA('也是可以找出来的,但是不符合预期结果。
var i,len,x:integer;
tmp:string;
begin
Result:=0;
len:=length(substr);
if len=0 then exit;
tmp:=s;
x:=0;
while length(tmp)>0 do
begin
i:=pos(substr,tmp);
if i>0 then
begin
if (i=1) then
begin
if not(tmp[len+1] in['a'..'z','A'..'Z']) then
begin
Result:=1;
exit;
end;
end
else if (not(tmp[i-1] in['a'..'z','A'..'Z']))and(not(tmp[i+len] in['a'..'z','A'..'Z'])) then
begin
Result:=x+i;
exit;
end
else
begin
x:=x+i+len-1;
tmp:=copy(tmp,i+len,length(tmp));
end;
end
else exit;
end;
end;procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
substr,s:string;
begin
substr:='AAA';
s:='(dsfsAAA ghtyAAAghfg AAAgfhgfh AAA)fdgfd';
i:=getLocation(substr,s);
if i>0 then showmessage('在第 '+inttostr(i)+' 个位置找字符 “'+substr+'"。')
else showmessage('字符串中找不到 “'+substr+'"。');
end;