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

一笑奈何 提交于 2019-12-20 02:02:48

问题


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.


回答1:


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');


来源:https://stackoverflow.com/questions/36938803/delphi-check-if-character-is-in-range-a-z-and-0-9

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