我有各种各样的字符串,我需要使用它们,它们包含字母和数字,我试图从字符串中提取数字(这是我需要的部分),字符串将具有类似的格式 -
这只猫可以算123 537
数字的长度和位置可以从12 34 123 456 1234 5678 11111 11111变化
数字分隔符也可以是空格问号,也可以是短划线12-34 12.34所以字符串可以是EG“猫不能算,狗可以12-67”或“猫可以算1234.5678所以可以狗“德尔福有什么聪明的方法可以提取数字吗?或者我必须通过扫描代码中的字符串来完成它。
任何帮助,将不胜感激
谢谢
科林
我认为这个功能正是你要找的:
function ExtractNumbers(const s: string): TArray<string>;
var
i, ItemIndex: Integer;
LastCharWasDigit: Boolean;
len: Integer;
Count: Integer;
Start: Integer;
begin
len := Length(s);
if len=0 then begin
Result := nil;
exit;
end;
Count := 0;
LastCharWasDigit := False;
for i := 1 to len do begin
if TCharacter.IsDigit(s[i]) then begin
LastCharWasDigit := True;
end else if LastCharWasDigit then begin
inc(Count);
LastCharWasDigit := False;
end;
end;
if LastCharWasDigit then begin
inc(Count);
end;
SetLength(Result, Count);
ItemIndex := 0;
Start := 0;
for i := 1 to len do begin
if TCharacter.IsDigit(s[i]) then begin
if Start=0 then begin
Start := i;
end;
end else begin
if Start<>0 then begin
Result[ItemIndex] := Copy(s, Start, i-Start);
inc(ItemIndex);
Start := 0;
end;
end;
end;
if Start<>0 then begin
Result[ItemIndex] := Copy(s, Start, len);
end;
end;
如果您有Delphi XE或更高版本,则可以使用正则表达式。根据David Heffernan的回答,这是完全未经测试的:
function ExtractNumbers(const s: string): TArray<string>;
var
regex: TRegEx;
match: TMatch;
matches: TMatchCollection;
i: Integer;
begin
Result := nil;
i := 0;
regex := TRegEx.Create("\d+");
matches := regex.Matches(s);
if matches.Count > 0 then
begin
SetLength(Result, matches.Count);
for match in matches do
begin
Result[i] := match.Value;
Inc(i);
end;
end;
end;
function ExtractNumberInString ( sChaine: String ): String ;
var
i: Integer ;
begin
Result := '' ;
for i := 1 to length( sChaine ) do
begin
if sChaine[ i ] in ['0'..'9'] then
Result := Result + sChaine[ i ] ;
end ;
end ;