int num_lines = 0, num_chars = 0;
%%
\n ++num_lines; ++num_chars;
. ++num_chars;
%%
int main()
{
yylex();
printf( "# of lines = %d, # of chars = %d\n", num_lines, num_chars );
}
%% 는 규칙의 시작을 나타낸다.
해당 코드는 줄 수와 문자의 수를 센다.
\n은 newline을 의미하며 새 줄이 입력될 때마다 num_lines 와 num_chars를 증가시킨다.
. 패턴은 모든 문자를 나타내고, 새 줄이 아닌 모든 문자를 발견할 때마다 num_chars를 증가시킨다.
main() 함수에서 yylex()가 호출되어 scanner가 동작하고 결과를 출력한다.
시작 조건 선언:
%s : 포함형 시작 조건 선언.
%x : 배타적 시작 조건 선언.
시작 조건은 BEGIN 액션을 통해 활성화.
%s expect
%%
expect-floats BEGIN(expect);
<expect>[0-9]+\.[0-9]+ {
printf("found a float, = %f\n", atof(yytext));
}
expect-floats: 문자열이 입력되면 부동 소수점 숫자를 인식해 이를 단일 토큰으로 처리하는 예시.
%x comment
%%
int line_num = 1;
"/*" BEGIN(comment);
<comment>[^*\n]* /* eat anything that's not a '*' */
<comment>"*"[^*/\n]* /* eat '*' not followed by '/' */
<comment>\n ++line_num;
<comment>"*"+"/" BEGIN(INITIAL);
이 것은 C스타일의 주석을 인식하고, 줄번호를 유지하며 주석을 처리하는 예시.