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

时光怂恿深爱的人放手 提交于 2019-12-01 19:33:30
fantaghirocco

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!