type
TDotPosInfo = record
Postion: integer;
strBefore: string[3];
strAfter: string[3];
end;
function FindFirstIP(sBuffer: string): string;
var
sStrBefore, sStrAfter: string;
iLen, iDotCount, iTemp, iLastDotPos,
i, k: integer;
Dots: array[1..3] of TDotPosInfo;
procedure CheckDotsInfo;
begin
if (Length(Dots[1].strBefore) = 3) and
(StrTointDef(Dots[1].strBefore, 256) > 255) then //288.1.1.1 --> 88.1.1.1
Delete(Dots[1].strBefore, 1, 1);
if (Length(Dots[1].strBefore) = 2) and
(Dots[1].strBefore[1] = '0') then //08.1.1.1 --> 8.1.1.1
Delete(Dots[1].strBefore, 1, 1);
if (Length(Dots[3].strAfter) = 3) and
(StrTointDef(Dots[3].strAfter, 256) > 255) then //1.1.1.288 --> 1.1.1.28
Delete(Dots[3].strAfter, 3, 1);
Result := Dots[1].strBefore + '.' + Dots[1].strAfter + '.' +
Dots[2].strAfter + '.' + Dots[3].strAfter;
end;
begin
iLen := Length(sBuffer);
if iLen < 7 then Exit;
iDotCount := 0;
iLastDotPos := 0;
for i := 2 to iLen do
//遇到一个'.' ,判断前后数据是否有效
if sBuffer = '.' then begin
if (iDotCount > 0) then
//两个'.' 之间字符数超过 3 ,重新开始
if (i - iLastDotPos - 1 > 3) then
iDotCount := 0
else begin
iTemp := StrToIntDef(Copy(sBuffer, iLastDotPos + 1, i - iLastDotPos - 1), 256);
//两个'.' 之间不是有效值,重新开始
if (iTemp < 0) or (iTemp > 255) then
iDotCount := 0;
end;
//取 '.' 前面的值
sStrBefore := '';
for k := i - 1 downto 1 do
if (sBuffer[k] in ['0'..'9']) then begin
sStrBefore := sBuffer[k] + sStrBefore;
if Length(sStrBefore) >= 3 then
Break;
end else begin
Break;
end;
//取 '.' 后面的值
sStrAfter := '';
for k := i + 1 to i + 4 do
if (k <= iLen) and (sBuffer[k] in ['0'..'9']) then begin
sStrAfter := sStrAfter + sBuffer[k];
if Length(sStrAfter) >= 3 then
Break;
end else begin
Break;
end;
//'.' 前面和后面都是有效值,则找到一个符合要求的,否则重新开始
if (sStrBefore <> '') and (sStrAfter <> '') then begin
Inc(iDotCount);
Dots[iDotCount].Postion := i;
Dots[iDotCount].strBefore := sStrBefore;
Dots[iDotCount].strAfter := sStrAfter;
end else
iDotCount := 0;
//按要求凑齐了 3 个 '.' 则找到 IP
if iDotCount = 3 then begin
//对前后处理一下
CheckDotsInfo;
Break
end;
iLastDotPos := i;
end;
end;