简体   繁体   English

Delphi-如何从字符串中提取数字?

[英]Delphi - How can I extract the digits from a character string?

I was developing a program that validate a CPF, a type of document of my country. 我正在开发一个程序来验证CPF,这是我国的一种文件。 I already did all the math. 我已经做了所有的数学运算。 But in the input Edit1, the user will insert like: 但是,在输入Edit1中,用户将插入:

123.456.789-00

I have to get only the numbers, without the hyphen and the dots, to my calcs worth. 我只需要计算数字,不包括连字符和点,就可以计算出我的计算值。

I'm newbie with Delphi, but I think that's simple. 我是Delphi的新手,但我认为这很简单。 How can I do that? 我怎样才能做到这一点? Thanks for all 谢谢大家

You can use 您可以使用

text := '123.456.789-00'
text := TRegEx.Replace(text, '\D', '')

Here, \\D matches any non-digit symbol that is replaced with an empty string. 在此, \\D与替换为空字符串的任何非数字符号匹配。

Result is 12345678900 (see regex demo ). 结果是12345678900 (请参阅regex演示 )。

Using David's suggestion, iterate your input string and remove characters that aren't numbers. 使用David的建议,迭代您的输入字符串并删除非数字字符。

{$APPTYPE CONSOLE}

function GetNumbers(const Value: string): string;
var
  ch: char;
  Index, Count: integer;
begin
  SetLength(Result, Length(Value));
  Count := 0;      
  for Index := 1 to length(Value) do
  begin
    ch := Value[Index];
    if (ch >= '0') and (ch <='9') then
    begin
      inc(Count);
      Result[Count] := ch;
    end;
  end;
  SetLength(Result, Count);
end;

begin
  Writeln(GetNumbers('123.456.789-00'));
  Readln;
end.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM