我需要检查字符串是否仅包含range:中的字符'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对问题的评论,System.Character.TCharHelper.IsLetterOrDigit可以替代上述逻辑:
if not Result[i].IsLetterOrDigit then
raise Exception.Create('Non valido');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句