簡體   English   中英

使用utf8格式的正則表達式過濾字符串

[英]Filtering string using regex in utf8 format

我試圖過濾掉特殊字符的字符串並將其轉換為小寫字符。 例如: "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;
}

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

因此,完整的正則表達式將是:

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

演示

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM