我有各种字符串需要使用,这些字符串包含字母和数字,我正在尝试从字符串中提取数字(这是我需要的部分),这些字符串将具有类似的格式-
猫能数123 567,狗也能数“
数字的长度和位置可以从12 34 123 456 1234 5678 11111 11111
此外,数字分隔符可以是空格问号和破折号12-34 12.34,因此字符串可以是EG“猫不会数,狗会12-67”或“猫会数1234.5678所以狗会数”,在Delphi中有什么聪明的方法可以提取数字吗?或者我必须通过扫描代码中的字符串来完成此操作。
任何帮助都将不胜感激
谢谢
科林
发布于 2012-01-12 01:19:12
我想这个函数就是你想要的:
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;发布于 2012-01-12 03:52:48
如果您有Delphi XE或更高版本,则可以使用正则表达式。这是完全未经测试的,基于大卫·赫弗南的答案:
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;发布于 2018-07-21 23:58:47
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 ;https://stackoverflow.com/questions/8823292
复制相似问题