【问题标题】:Filtering string using regex in utf8 format使用 utf8 格式的正则表达式过滤字符串
【发布时间】:2019-10-07 13:48:30
【问题描述】:

我正在尝试过滤转义特殊字符并将其转换为小写的字符串。例如:"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;
}

【问题讨论】:

  • “ąžuolas!”的预期输出是什么? ?
  • 应该输出ąžuolas

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


【解决方案1】:

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

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

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

Demo

Source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多