Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!
Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.
Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!
[Solved] Lazarus - Remove all (non)numbers from a string
Delphi, Lazarus, Free Pascal
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter
August 31, 2018 1:30 AM
When writing one of my small applications I ran into the issue that I had to remove all non-numbers from a string.
I came up with this little function and thought it may be useful to others.
I've also added an example for those who only want to remove numbers from a string (so the opposite).
function RemoveAllNonNumbers(aText:string):string;
var
Character:Char;
begin
for Character in aText do
if CharInSet(Character,['0'..'9']) then
Result := Result + Character;
end;
The opposite:
function RemoveAllNumbers(aText:string):string;
var
Character:Char;
begin
for Character in aText do
if not CharInSet(Character,['0'..'9']) then
Result := Result + Character;
end;
Hope this is useful to someone 
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter
April 2, 2025 3:21 AM
If you only want to grab all the numbers until you reach a non-number (eg: 123example456 -> 123) then this will do the trick:
function RemoveAllNonNumbers(aText:string):string;
var
Character : Char;
begin
Result := '';
for Character in aText do
if CharInSet(Character,['0'..'9']) then
Result := Result + Character
else
exit;
end;