我需要根据 Edittext.text
使用不同的过程
如果 ProcessA(value: string);
的前 4 个字符是字符串,接下来的 4 个字符是数字,我需要使用字符串最后 4 个字符的参数来调用 Edittext.text
。
如果所有 8 个字符都是数字,则使用最后四个数字作为参数调用 ProcessB(value:integer)
?
例如:如果 EditText.Text
是 ASDF1234
那么我将调用 ProcessA
如果 EdiText.Text
是 12345678
那么我需要调用 ProcessB
。
如果字符串类似于 ASD12345
或 ASDFG123
或 1234567A
或者数字为十进制,则显示错误。
我如何验证这一点?
最佳答案
var
Text: string;
function CharInRange(C, FirstC, LastC: char): boolean; inline;
begin
Result := (C >= FirstC) and (C <= LastC);
end;
function IsDigitsOnly(const S: string;
FirstIdx, LastIdx: integer): boolean;
var
I: integer;
begin
for I := FirstIdx to LastIdx do
begin
if not CharInRange(S[I], '0', '9') then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function IsUpcaseLettersOnly(const S: string;
FirstIdx, LastIdx: integer): boolean;
var
I: integer;
C: char;
begin
for I := FirstIdx to LastIdx do
begin
C := S[I];
if not CharInRange(C, 'A', 'Z') then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
procedure BadInput;
begin
raise Exception.Create('Bad Input');
end;
begin
Text := EditText.Text;
if Length(Text) <> 8 then
begin
BadInput;
end
else if IsUpcaseLettersOnly(Text, 1, 4)
and IsDigitsOnly(Text, 5, 8) then
begin
ProcessA(Copy(Text, 5, 4));
end
else if IsDigitsOnly(Text, 1, 8) then
begin
ProcessB(StrToInt(Copy(Text, 5, 4)));
end
else
begin
BadInput;
end;
end;
或者
uses
..., System.RegularExpressions;
var
Text: string;
begin
Text := EditText.Text;
// I know this can be done better using a
// single regex expression with capture groups,
// but I don't know the correct code to do that...
if TRegEx.IsMatch(Text, '^[A-Z]{4}[0-9]{4}$') then
begin
ProcessA(Copy(Text, 5, 4));
end
else if TRegEx.IsMatch(Text, '^[0-9]{8}$') then
begin
ProcessB(StrToInt(Copy(Text, 5, 4)));
end
else
begin
raise Exception.Create('Bad Input');
end;
end;
关于Delphi FMX 验证 EditText 是否仅包含数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56182176/