Skip to content

Instantly share code, notes, and snippets.

@aagontuk
Last active July 30, 2020 14:05
Show Gist options
  • Select an option

  • Save aagontuk/0018fcbf9cbc978350b86e04916711ef to your computer and use it in GitHub Desktop.

Select an option

Save aagontuk/0018fcbf9cbc978350b86e04916711ef to your computer and use it in GitHub Desktop.
Lex rule for generating lexical analyzer to match US phone numbers

Lex rule for generating lexical analyzer to match US phone numbers.

%{
    int isValid = 0;
%}

digit   [0-9]
valid   {digit}{3,3}-{digit}{3,3}-{digit}{4,4}

%%
{valid}  {isValid = 1;}
. {isValid = 0;}
\n  {return 0;}
%%

int yywrap() {}
int main() {
    while(1) {
        yylex();
        if(isValid) {
            printf("Valid!\n");
        }
        else {
            printf("Invalid!\n");
        }
    }

    return 0;
}

To compile & Run

$ sudo apt update
$ sudo apt install flex
$ lex phnum.l
$ gcc lex.yy.c
$ ./a.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment