Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi check if character is in range 'A'..'Z' and '0'..'9'

I need to check if a string contains only characters from ranges: 'A'..'Z', 'a'..'z', '0'..'9', so I wrote this function:

function GetValueTrat(aValue: string): string;
const
  number = [0 .. 9];
const
  letter = ['a' .. 'z', 'A' .. 'Z'];
var
  i: Integer;
begin

  for i := 1 to length(aValue) do
  begin
    if (not(StrToInt(aValue[i]) in number)) or (not(aValue[i] in letter)) then
      raise Exception.Create('Non valido');
  end;

  Result := aValue.Trim;
end;

but if for example, aValue = 'Hello' the StrToInt function raise me an Exception.

like image 828
img.simone Avatar asked Apr 29 '16 12:04

img.simone


1 Answers

An unique set of Char can be used for your purpose.

function GetValueTrat(const aValue: string): string;
const
  CHARS = ['0'..'9', 'a'..'z', 'A'..'Z'];
var
  i: Integer;
begin
  Result := aValue.Trim;
  for i := 1 to Length(Result) do
  begin
    if not (Result[i] in CHARS) then
      raise Exception.Create('Non valido');
  end;
end;

Notice that in your function if aValue contains a space character - like 'test value ' for example - an exception is raised so the usage of Trim is useless after the if statement.


A regular expression like ^[0-9a-zA-Z] can solve your issue in a more elegant way in my opinion.


EDIT
According to the @RBA's comment to the question, System.Character.TCharHelper.IsLetterOrDigit can be used as a replacement for the above logic:

if not Result[i].IsLetterOrDigit then
  raise Exception.Create('Non valido');
like image 95
fantaghirocco Avatar answered Oct 12 '22 14:10

fantaghirocco