Delphi检查字符是否在'A'..'Z'和'0'..'9'范围内 [英] Delphi check if character is in range 'A'..'Z' and '0'..'9'

查看:488
本文介绍了Delphi检查字符是否在'A'..'Z'和'0'..'9'范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查字符串是否仅包含范围内的字符:'A'..'Z', 'a'..'z', '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;

但是例如,如果aValue = 'Hello' StrToInt函数引发异常.

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

推荐答案

一组独特的Char可用于您的目的.

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;

请注意,在函数中,如果aValue包含空格字符(例如'test value '),则会引发异常,因此在if语句后使用Trim是无用的.

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.

在我看来,像^[0-9a-zA-Z]这样的正则表达式可以更优雅地解决您的问题.

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

编辑
根据 @RBA的评论 System.Character.TCharHelper.IsLetterOrDigit 可以替代上述逻辑:

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

这篇关于Delphi检查字符是否在'A'..'Z'和'0'..'9'范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆