简体   繁体   中英

lex pattern to match ipv4 dotted decimal notation

I have a pattern that is given below to match an ipv4 address in the dotted decimal notation.

IPV4ADDRESS (([[:digit:]]{1,3}"."){3}([[:digit:]]{1,3}))

and I use

%x S_rule S_dst_ip

<S_rule>(dst-ip){SPACE}   {

           BEGIN(S_dst_ip);

        }


<S_dst_ip>\{{IPV4ADDRESS}\}  {

       /*code to process the sring here.*/
     }

to match an input of the form

dst-ip {10.13.12.138}

Now I want to match

dst-ip { 10.13.12.138 } in addition to dst-ip {10.13.12.138}

I modify the IPV4ADDRESS defined above as follows

IPV4ADDRESS [ \t]*(([[:digit:]]{1,3}"."){3}([[:digit:]]{1,3}))[ \t]*

However this modification doesn't seem to match

  dst-ip { 10.13.12.138 } OR dst-ip {10.13.12.138}

Can someone point out the error in my code ?

Since it 'works for me', I can't tell you what's wrong with your code as you've not shown an SSCCE ( Short, Self-Contained, Correct Example ). Here's one:

/*IPV4ADDRESS     (([[:digit:]]{1,3}"."){3}([[:digit:]]{1,3}))*/
IPV4ADDRESS [ \t]*(([[:digit:]]{1,3}"."){3}([[:digit:]]{1,3}))[ \t]*
SPACE [ \t]

%x S_rule S_dst_ip

%%

%{
    BEGIN S_rule;
%}

<S_rule>(dst-ip){SPACE}   {
           BEGIN(S_dst_ip);
        }

<S_dst_ip>\{{IPV4ADDRESS}\}  {
       printf("\n\nMATCH [%s]\n\n", yytext);
       BEGIN S_rule;
     }

. { ECHO; }

%%

int main(void)
{
    while (yylex() != 0)
        ;
    return(0);
}

int yywrap(void)
{
    return 1;
}

Using a test data file based on text from your question:

dst-ip {10.13.12.138}
dst-ip { 10.13.12.138 } 
dst-ip {10.13.12.138}
dst-ip { 10.13.12.138 } OR dst-ip {10.13.12.138}

The program above produces (some blank lines elided):

MATCH [{10.13.12.138}]

MATCH [{ 10.13.12.138 }]

MATCH [{10.13.12.138}]

MATCH [{ 10.13.12.138 }]

 OR 

MATCH [{10.13.12.138}]

If I had to guess what's going wrong, I'd suspect that you're missing the switch back to state S_rule after recognizing S_dst_ip (and possibly the opening %{ BEGIN S_rule; %} phrase too).

I note in passing that this will accept {999.999.999.999} as an IPv4 address. However, it's feasible to fix that with a more tightly controlled expression, and isn't germane to your main problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM