使用utf8格式的正则表达式过滤字符串

时间:2019-05-21 07:54:45

标签: c++ regex unicode utf-8 c++14

我正在尝试过滤转义特殊字符的字符串并将其转换为小写。例如:"Good morning!"转换为good morning
我当时要向函数传递一个字符串。
我已成功过滤了英语字符串,但传递本地语言字符串时出现问题。
如果要包含所有utf-8字符,应该使用哪种类型的正则表达式过滤器字符串?

#include <string>
#include <iostream>
#include <regex>
#include <algorithm>

std::string process(std::string s) {
    std::string st;
    std::regex r(R"([^\W_]+(?:['_-][^\W_]+)*)");
    std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
    std::smatch m = *i;
    st = m.str();
    std::transform(st.begin(), st.end(), st.begin(), ::tolower);
    return st;
}

int main() {
    std::string st = "ąžuolas!";
    std::cout << process(st) << std::endl; // <- gives: uolas
    return 0;
}

1 个答案:

答案 0 :(得分:6)

您可以使用正则表达式\p{L}\p{M}*匹配任何Unicode“字母”字符。

因此,完整的正则表达式将为:

((?:\p{L}\p{M}*)+(?:['_-](?:\p{L}\p{M}*)+)*)

Demo

Source