我需要检查字符串是否仅包含以下范围内的字符:'A'..'Z'、'a'..'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;
但是,例如,如果aValue = 'Hello'
,StrToInt
函数会引发异常。
最佳答案
一组独特的Char
可用于您的目的。
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 '
- 会引发异常,因此使用 Trim
在 if
语句之后就没用了。
在我看来,像 ^[0-9a-zA-Z]
这样的正则表达式可以以更优雅的方式解决您的问题。
编辑
根据@RBA's comment对于这个问题,System.Character.TCharHelper.IsLetterOrDigit可以用来替代上述逻辑:
if not Result[i].IsLetterOrDigit then
raise Exception.Create('Non valido');
关于arrays - Delphi 检查字符是否在 'A' 范围内。 .'Z' 和 '0' 。 .'9',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938803/