2

我正在尝试验证一个字符串,它可以包含所有字母和数字字符,以及下划线 (_) 符号。

这是我到目前为止所尝试的:

var
  S: string;
const
  Allowed = ['A'..'Z', 'a'..'z', '0'..'9', '_'];
begin
  S := 'This_is_my_string_0123456789';

  if Length(S) > 0 then
  begin
    if (Pos(Allowed, S) > 0 then
      ShowMessage('Ok')
    else
      ShowMessage('string contains invalid symbols');
  end;
end;

在拉撒路这个错误与:

错误: arg no 的类型不兼容。1:得到“Set Of Char”,预期“Variant”

显然我对 Pos 的使用都是错误的,我不确定我的方法是否是正确的方法?

谢谢。

4

3 回答 3

9

您必须检查字符串的每个字符,如果它包含在Allowed中

例如:

var
  S: string;
const
  Allowed = ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_'];

  Function Valid: Boolean;
  var
    i: Integer;
  begin
    Result := Length(s) > 0;
    i := 1;
    while Result and (i <= Length(S)) do
    begin
      Result := Result AND (S[i] in Allowed);
      inc(i);
    end;
    if  Length(s) = 0 then Result := true;
  end;

begin
  S := 'This_is_my_string_0123456789';
  if Valid then
    ShowMessage('Ok')
  else
    ShowMessage('string contains invalid symbols');
end;
于 2013-09-08T11:27:48.390 回答
3
TYPE TCharSet = SET OF CHAR;

FUNCTION ValidString(CONST S : STRING ; CONST ValidChars : TCharSet) : BOOLEAN;
  VAR
    I : Cardinal;

  BEGIN
    Result:=FALSE;
    FOR I:=1 TO LENGTH(S) DO IF NOT (S[I] IN ValidChars) THEN EXIT;
    Result:=TRUE
  END;

如果您使用的是 Unicode 版本的 Delphi(您似乎是这样),请注意 SET OF CHAR 不能包含 Unicode 字符集中的所有有效字符。那么也许这个函数会很有用:

FUNCTION ValidString(CONST S,ValidChars : STRING) : BOOLEAN;
  VAR
    I : Cardinal;

  BEGIN
    Result:=FALSE;
    FOR I:=1 TO LENGTH(S) DO IF POS(S[I],ValidChars)=0 THEN EXIT;
    Result:=TRUE
  END;

但话又说回来,并非 Unicode 中的所有字符(实际上是 Codepoints)都可以用单个字符表示,有些字符可以用不止一种方式表示(既可以作为单个字符也可以作为多字符)。

但只要您将自己限制在这些限制范围内,上述功能之一应该是有用的。如果您添加“OVERLOAD”,您甚至可以同时包含两者。指令到每个函数声明的末尾,如下所示:

FUNCTION ValidString(CONST S : STRING ; CONST ValidChars : TCharSet) : BOOLEAN; OVERLOAD;
FUNCTION ValidString(CONST S,ValidChars : STRING) : BOOLEAN; OVERLOAD;
于 2013-09-08T13:00:58.757 回答
2

Lazarus/Free Pascal 不会为此重载 pos,但在 unit strutils 中有“posset”变体;

http://www.freepascal.org/docs-html/rtl/strutils/posset.html

关于 Andreas(恕我直言,正确)的评论,您可以使用 isemptystr 。它旨在检查仅包含空格的字符串,但它基本上检查字符串是否仅包含集合中的字符。

http://www.freepascal.org/docs-html/rtl/strutils/isemptystr.html

于 2013-09-08T12:45:11.117 回答