Delphi检查字符是否在“A”范围内。“Z”和“0”…“9”

时间:2022-03-20 20:13:28

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

我需要检查一个字符串是否只包含范围的字符:' a '..“Z”、“‘. .' z ',' 0 ' . .“9”,所以我写了这个函数

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.

但是如果举个例子,aValue = 'Hello'这个StrToInt函数会给我一个异常。

1 个解决方案

#1


7  

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.

请注意,如果aValue包含空格字符(例如“测试值”),那么就会出现异常,因此在if语句之后,Trim的用法是没有用的。


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

一个正则表达式如^[0-9a-zA-Z]更优雅的方式可以解决你的问题在我看来。


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

根据@RBA对问题的评论,system .字符。tcharhelper。IsLetterOrDigit可作为上述逻辑的替代:

if not Result[i].IsLetterOrDigit then
  raise Exception.Create('Non valido');

#1


7  

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.

请注意,如果aValue包含空格字符(例如“测试值”),那么就会出现异常,因此在if语句之后,Trim的用法是没有用的。


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

一个正则表达式如^[0-9a-zA-Z]更优雅的方式可以解决你的问题在我看来。


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

根据@RBA对问题的评论,system .字符。tcharhelper。IsLetterOrDigit可作为上述逻辑的替代:

if not Result[i].IsLetterOrDigit then
  raise Exception.Create('Non valido');