RegEx in Delphi

4

A help with regular expressions in Delphi 10 please. I need to check the following in string :

  • Size ranging from a minimum of 6 characters to a maximum of 20 characters;
  • Type of characters: a-z or A-Z or 0-9 or _ (underline character);
  • The allowed characters can be in any position and in any quantity (up to the limit of the string, of course);
  • Examples

    VALID STRINGS :

    AaaaaaaaBCCcc654_qq
    1111s123AaBCcc654_qq
    ____ds4___xx
    12345_123
    

    INVALID STRINGS :

    12345-123            (tem hífen)
    asdkdn  092834sdfdf  (tem espaco em branco)
    $123.0               (tem "$" e ".")
    

    I tried things like these, but they did not work:

    var ret: TMatch;
    begin
       ret := TRegEx.Match(Edit1.Text, '([a-z]*[A-Z]*[0-9]*[-]?)', [roIgnoreCase]);
    

    or

       ret := TRegEx.Match(Edit1.Text, '(\w*)', [roIgnoreCase]);
    
        
    asked by anonymous 04.12.2017 / 15:25

    1 answer

    5
    • \w home a-z , A-Z , 0-9 or _ .
    • Just repeat 6 to 20 times, that's \w{6,20}
    • From the beginning of the string ^ to the end of the string $ .

    Then:

    ^\w{6,20}$
    

    And in this case, it's easier to use the TRegEx.IsMatch ()

    Code:

    {$APPTYPE CONSOLE}
    
    uses
        System.RegularExpressions;
    
    var texto: string;
    
    begin
        texto := 'AaaaaaaaBCCcc654_qq';
    
        if TRegEx.IsMatch(texto, '^\w{6,20}$') then
            begin
                Writeln(texto, ' é válido');
            end
        else
            begin
                Writeln(texto, ' não é válido');
            end;
    end.
    
        
    04.12.2017 / 16:27