You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写匹配URL协议/域名/端口/路径的Flex代码遇编译错误求助

解决Flex编译错误并修正URL匹配代码

错误原因

task1.l:9: unrecognized rule 一般是规则行的正则语法不符合Flex规范,或者规则与后续动作代码的格式不匹配(比如缺少空格分隔、动作代码语法错误)。

修正后的完整代码

%{
#include <stdio.h>
#include <string.h>
%}

// 定义正则片段,提升可读性
PROTOCOL   https?://
DOMAIN     [a-zA-Z0-9.-]+
PORT       :[0-9]+
PATH       /.*

%%
{PROTOCOL}{DOMAIN}({PORT})?({PATH})? {
    // 提取协议类型
    char proto[10];
    sscanf(yytext, "%[^://]", proto);
    printf("协议: %s\n", proto);
    
    // 定位域名起始位置(跳过http://或https://)
    int domain_start = strlen(proto) + 3; // proto长度 + "://"的3个字符
    char* domain_ptr = yytext + domain_start;
    
    // 处理端口和路径
    char* port_ptr = strchr(domain_ptr, ':');
    if (port_ptr) {
        *port_ptr = '\0'; // 截断域名部分
        printf("域名: %s\n", domain_ptr);
        
        port_ptr++;
        char* path_ptr = strchr(port_ptr, '/');
        if (path_ptr) {
            *path_ptr = '\0';
            printf("端口: %s\n", port_ptr);
            printf("路径: %s\n", path_ptr);
        } else {
            printf("端口: %s\n", port_ptr);
        }
    } else {
        char* path_ptr = strchr(domain_ptr, '/');
        if (path_ptr) {
            *path_ptr = '\0';
            printf("域名: %s\n", domain_ptr);
            printf("路径: %s\n", path_ptr);
        } else {
            printf("域名: %s\n", domain_ptr);
        }
    }
    printf("-------------------------\n");
}
.|\n {
    printf("无效URL: %s", yytext);
}
%%

int main() {
    yylex();
    return 0;
}

int yywrap() {
    return 1;
}

编译运行步骤

  1. 把代码存为task1.l
  2. 用Flex编译:flex task1.l
  3. GCC编译生成可执行文件:gcc lex.yy.c -o url_parser
  4. 运行程序:./url_parser,输入测试URL即可看到结果。

测试示例

输入:

http://example.com
https://blog.example.com:8080/post/123
http://test.io:9000

输出:

协议: http
域名: example.com
-------------------------
协议: https
域名: blog.example.com
端口: 8080
路径: /post/123
-------------------------
协议: http
域名: test.io
端口: 9000
-------------------------

内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:27:32