1

I was developing a program that validate a CPF, a type of document of my country. I already did all the math. But in the input Edit1, the user will insert like:

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. How can I do that? Thanks for all

2
  • 1
    Perhaps, TRegEx.Replace(s, '\D', '')? (\D is a non-digit, and \W is a non-word character, both should work). Commented Nov 6, 2015 at 21:23
  • Loop through the string picking out the digits Commented Nov 6, 2015 at 21:35

2 Answers 2

4

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.

Result is 12345678900 (see regex demo).

Sign up to request clarification or add additional context in comments.

Comments

2

Using David's suggestion, iterate your input string and remove characters that aren't numbers.

{$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.

6 Comments

Be nice to avoid as many of those heap allocations as you can.
@DavidHeffernan: Not meaning to be obtuse, but I'm curious about what you have in mind regarding "Be nice ...". Do you meant counting the number of digit occurrences first, then allocating space for the Result based on that, or what?
@Martyn That. Or allocate string of same length as result, populate, and size before exit. Two heap allocs.
@John Also worth pointing out that in with Unicode text will lead to warnings. I'd use (ch >= '0') and (ch <= '9')
Yes. I corrected the off by one error. I'd still reduce the heap allocs were it me, but perhaps I'm being picky.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.