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

使用C++正则解析器提取Gcode中XY坐标及遇G92停止的问题

解决Gcode解析问题:提取XY坐标、仅处理G1行、遇G92停止

原代码的问题

  1. 正则表达式错误:[XY].?\\d+.\\d+中,.未转义会匹配任意字符;且该正则只能单次匹配一个坐标(X或Y),无法获取一行中的所有XY坐标,同时coord_match[1]无对应捕获组,导致输出异常。
  2. 缺少核心逻辑:未实现仅处理含G1的行,也未在遇到G92时停止解析。

修改后的代码

#include <iostream>
#include <fstream>
#include <string>
#include <regex>

using namespace std;

int main()
{
    ifstream gcode("circuit.gcode");
    if (!gcode.is_open()) {
        cerr << "无法打开文件" << endl;
        return 1;
    }

    string line;
    // 匹配X/Y坐标,支持正负整数、小数格式(如X10、Y-5.2)
    regex coord_regex(R"([XY](-?\d+(\.\d+)?))");
    smatch coord_match;

    while (getline(gcode, line))
    {
        // 遇到G92立即终止解析
        if (line.find("G92") != string::npos) {
            break;
        }

        // 仅处理包含G1的行
        if (line.find("G1") == string::npos) {
            continue;
        }

        // 全局搜索一行内的所有XY坐标
        string::const_iterator search_start(line.cbegin());
        while (regex_search(search_start, line.cend(), coord_match, coord_regex)) {
            cout << coord_match[0] << " ";
            search_start = coord_match.suffix().first;
        }
        if (!coord_match.empty()) {
            cout << endl;
        }
    }

    gcode.close();
    return 0;
}

代码说明

  • 文件合法性检查:增加文件打开失败的判断,避免程序异常崩溃。
  • 停止解析逻辑:每行优先检查是否包含G92,满足则直接跳出循环终止解析。
  • 过滤目标行:仅对包含G1的行进行坐标提取,跳过无关行。
  • 正则表达式优化:使用原始字符串避免转义混乱,支持匹配正负整数、小数格式的X/Y坐标。
  • 全局匹配处理:通过循环调用regex_search,获取一行中的所有XY坐标,解决原代码仅提取单个坐标的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:31:22