Saturday, 15 October 2016

yytext, yyleng



When a character string matches some pattern in the lex specification, it is stored in a character array called yytext. The contents of this array may be operated on by the action associated with the pattern: it can be printed or manipulated as necessary. lex also provides a variable yyleng, which gives the number of characters matched by the pattern.
For example, the following rule directs the lexical analyzer to count the digit strings in an input text and print the running total, and print out the text of each string as soon as it is found:
   %{
   int digstringcount=0;
   %}
   %%
   [-+]?[0-9]+     {
                           digstringcount++;
                           printf("%d %s\n",digstringcount,yytext);
                   }
This specification matches negative digit strings, and positive strings whether or not they are preceded by a plus sign; the ``?'' indicates that the preceding sign is optional.

No comments:

Post a Comment