C++之正则使用方法

十年热恋 提交于 2020-02-04 12:20:07

这里总结一下c++标准库中正则类的相关使用方法。

#include <string>
#include <regex>
using namespace std;
//入参用&,指向同一个字符串,否则相同字符串会被拷贝后传入函数
string rm_surplus_spaces(string &s) {
    regex r("\\s+");
    string new_s = regex_replace(s, r, " ");
    return new_s;
}
//基于正则,做全局替换的函数,主要是将中文的符号转为英文
string replace_all(string &s, const string &old_value, const string &new_value) {
    regex re(old_value);
    string ss = regex_replace(s, re, new_value);
    return ss;
}
//regex_search的例子
void test_regex_search(string &test_str, string &pattern) {
    regex r(pattern);
    //当定义it时,sregex_iterator的构造函数调用regex_search将it定位到第一个与r匹配的位置。it_end是迭代器是否结尾的标识。
    sregex_iterator it(test_str.begin(), test_str.end(), r);
    sregex_iterator it_end;
    //while中的递增运算通过regex_search来推进迭代器,即++it一次,就执行一次regex_search
    while (it != it_end) {
        cout << it->str() << endl;
        ++it;
    }
}
int main() {
    string s = " 武汉,加,油。。中国,。加,油!";
    cout << s << endl;
    //不能用[,。], 因为每个字符都是多个byte的wide char,而[]中要求是ascii,这涉及到[]对于character class的支持力度,当前对wide char支持不好
    string old_value = "(,|。)+"; 
    string new_value = ",";
    cout << "addr_outside_s: " << &s << endl;
    string s_out = replace_all(s, old_value, new_value);
    cout << s_out << endl;

	string test_str = "receipt freind theif receive";
	string pattern("[^c]ei");
	pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
	test_regex_search(test_str, pattern);
}

额外notes:

  1. 正则[,。]的验证过程中,尝试过wstring和wregex & wcout,效果也不好。其中,wstring vs. string的对比和何时用哪个,可查看stackoverflow这篇提问的第一条热门回复。https://stackoverflow.com/questions/402283/stdwstring-vs-stdstring 若你的开发环境是linux/mac os,完全不需要。
  2. clion中,若用cmake编译,则记得在cmake的配置文件中加上debug模式相关参数。若直接debug 可执行文件,则g++生成可执行文件时,加上-g,如:

    g++ -o regex NameParserTest.cpp -g

先写到这儿,后续再更新。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!