Expressions regulars amb C

De Wikijoan
Dreceres ràpides: navegació, cerca

Per validar un mail: prova_regex.c:

#include <stdio.h>
#include <regex.h>

int main(const char *argv, int argc)
{
    //validació de mail
    const char *reg_exp = "^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))@([a-z0-9])([a-z0-9-])*([a-z0-9])([.])(([a-z0-9]){2,4})$";
    //el * significa tants caràcters com vulguis
    int status = 1;
    char *email;
    regex_t preg;
    int rc;

    printf("The regex = %s\n", reg_exp);
$ ./prova_regex2 
The regex = ^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))@([a-z0-9])([a-z0-9-])*([a-z0-9])([.])(([a-z0-9]){2,4})$
main: The regular expression is a match
    rc = regcomp(&preg, reg_exp, REG_EXTENDED|REG_NOSUB);
    if (rc != 0)
    {
        if (rc == REG_BADPAT || rc == REG_ECOLLATE)
            fprintf(stderr, "Bad Regex/Collate\n");
        if (rc == REG_ECTYPE)
            fprintf(stderr, "Invalid Char\n");
        if (rc == REG_EESCAPE)
            fprintf(stderr, "Trailing \\\n");
        if (rc == REG_ESUBREG || rc == REG_EBRACK)
            fprintf(stderr, "Invalid number/[] error\n");
        if (rc == REG_EPAREN || rc == REG_EBRACE)
            fprintf(stderr, "Paren/Bracket error\n");
        if (rc == REG_BADBR || rc == REG_ERANGE)
            fprintf(stderr, "{} content invalid/Invalid endpoint\n");
        if (rc == REG_ESPACE)
            fprintf(stderr, "Memory error\n");
        if (rc == REG_BADRPT)
            fprintf(stderr, "Invalid regex\n");

        fprintf(stderr, "%s: Failed to compile the regular expression:%d\n", __func__, rc);
        return 1;
    }

    email = "joanqcgma-i.lcom.ewrw@erwa-a.sdf";

    rc = regexec(&preg, email, (size_t)0, NULL, 0);
    if (rc == 0)
    {
        fprintf(stderr, "%s: The regular expression is a match\n", __func__);
    }
    else
    {
        fprintf(stderr, "%s: The regular expression is not a match: %d\n", __func__, rc);
    }


    regfree(&preg);

    return 0;

}
$ gcc prova_regex2.c -o prova_regex2
$ gcc prova_regex.c -o prova_regex
$ ./prova_regex
The regex = ^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))@([a-z0-9])([a-z0-9-])*([a-z0-9])([.])(([a-z0-9]){2,4})$
main: The regular expression is a match

creat per Joan Quintana Compte, març 2013

Eines de l'usuari
Espais de noms
Variants
Accions
Navegació
IES Jaume Balmes
Màquines recreatives
CNC
Informàtica musical
joanillo.org Planet
Eines