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

如何在C++中用正则匹配特定符号前的首部内容(含中文场景)

提取特定符号前的首部内容(C++正则问题)

需求是提取字符串中**英文.、英文,、中文,**之前的首部内容,示例:

  • 输入"ABC, ZXC",期望输出"ABC"
  • 输入"AB.QWE,CV",期望输出"AB"
  • 输入"1月1日,天气晴",期望输出"1月1日"

已通过Python实现该功能(修正原代码笔误后):

import re
front_part = re.findall(r'(.*?)[.,,]', content)[0] if re.findall(r'[.,,]', content) else content

但自行编写的C++正则代码始终返回完整字符串,代码如下:

#include<regex>
#include<string>
#include<iostream>
int main()
{
std::string content = "AB.AC";
std::string front_part;
std::smatch frt_pt_sm;
std::regex frt_pt_patt(".*[.,]");
if (std::regex_match(content, frt_pt_sm, frt_pt_patt))
{
for(unsigned i = 0;i < frt_pt_sm.size(); ++i)
{
std::cout<< frt_pt_sm[i] << std::endl;
} 
front_part = frt_pt_sm[0];
}
return 0;
}

问题原因

你的C++正则代码存在三个核心问题:

  1. .*是贪婪匹配模式,会尽可能匹配到最后一个目标符号,导致返回从开头到最后一个符号的全部内容,而非第一个符号前的部分;
  2. 正则未包含中文逗号,,且没有设置捕获分组,无法单独提取符号前的内容;
  3. regex_match要求整个字符串完全匹配正则规则,若字符串末尾没有目标符号,匹配会直接失败,无法返回原字符串。

解决方案

方案1:修正正则表达式(非贪婪捕获)

使用非贪婪匹配+捕获分组,同时加入中文逗号的匹配,并用regex_search替代regex_match(只需字符串中存在匹配部分即可生效):

#include<regex>
#include<string>
#include<iostream>
int main()
{
    std::string content = "AB.AC";
    std::string front_part = content; // 默认返回原字符串
    std::smatch match_result;
    // 正则解释:
    // (.*?):非贪婪捕获分组,匹配任意字符直到遇到第一个目标符号
    // [.,,]:匹配英文点、英文逗号、中文逗号
    std::regex patt(R"((.*?)[.,,])");

    if (std::regex_search(content, match_result, patt))
    {
        front_part = match_result[1]; // 取第一个捕获分组的内容
    }

    std::cout << front_part << std::endl;
    return 0;
}

方案2:不使用正则,直接查找符号位置

如果只是简单提取首个符号前的内容,用字符串原生查找函数效率更高,也更易理解:

#include<string>
#include<iostream>
int main()
{
    std::string content = "1月1日,天气晴";
    std::string front_part = content;

    // 查找第一个目标符号的位置
    size_t pos = content.find_first_of(".,,");
    if (pos != std::string::npos)
    {
        front_part = content.substr(0, pos);
    }

    std::cout << front_part << std::endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:30:59