IPv4 addressΒΆ

This example demonstrates how to use tags to parse simple things like IPv4 address.

[ipv4.re]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

static int lex(const char *YYCURSOR)
{
    const char *YYMARKER, *o1, *o2, *o3, *o4;
    /*!stags:re2c format = 'const char *@@;'; */
    /*!re2c
        re2c:define:YYCTYPE = char;
        re2c:yyfill:enable = 0;

        end = "\x00";
        oct = [0-9]{1,3};
        dot = ".";

        * { printf("error\n"); return 1; }

        @o1 oct dot @o2 oct dot @o3 oct dot @o4 oct {
            printf("parsed: %.*s, %.*s, %.*s, %*s!\n",
                (int)(o2 - o1 - 1), o1,
                (int)(o3 - o2 - 1), o2,
                (int)(o4 - o3 - 1), o3,
                (int)(YYCURSOR - o4), o4);
            return 0;
        }
    */
}

int main(int argc, char **argv)
{
    for (int i = 1; i < argc; ++i) lex(argv[i]);
    return 0;
}

Compile:

$ re2c --tags -o ipv4.cc ipv4.re
$ g++ -o ipv4 ipv4.cc

Run:

$ ./ipv4 127.0.0.1 192.168.1.255
parsed: 127, 0, 0, 1!
parsed: 192, 168, 1, 255!