只允许字符串中的某些字符



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

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

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;

在拉撒路中,此错误为:

错误:参数 1 的类型不兼容:预期获得"字符集" "变体"

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

谢谢。

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

例如:

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;
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 中的所有字符(实际上是 Codepoint)都可以用单个字符表示,并且某些字符可以用多种方式表示(作为单个字符和多字符)。

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

FUNCTION ValidString(CONST S : STRING ; CONST ValidChars : TCharSet) : BOOLEAN; OVERLOAD;
FUNCTION ValidString(CONST S,ValidChars : STRING) : BOOLEAN; OVERLOAD;

Lazarus/Free Pascal 不会为此重载 pos,但在单位 strutils 中有"posset"变体;

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

关于安德烈亚斯(恕我直言)的评论,您可以使用 isemptystr 来做到这一点。它旨在检查仅包含空格的字符串,但它基本上检查字符串是否仅包含集合中的字符。

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

您可以使用正则表达式:

uses System.RegularExpressions;

if not TRegEx.IsMatch(S, '^[_a-zA-Z0-9]+$') then
  ShowMessage('string contains invalid symbols');

最新更新