【问题标题】:replace or remove characters that are not in regex with c++用 c++ 替换或删除不在正则表达式中的字符
【发布时间】:2015-03-10 12:30:17
【问题描述】:

我想用 C++ 删除或替换任何不包含在正则表达式中的字符。 例如,如果表达式为:[a-z] 且字符串为:“Hello-World”,则返回字符串将为:“Hello World”,因为只允许使用 a-z。

谢谢

【问题讨论】:

    标签: c++ regex whitelist


    【解决方案1】:

    这是一个使用 C++ 正则表达式执行所需操作的示例程序:

    #include <iostream>
    #include <regex>
    #include <sstream>
    #include <string>
    
    int main(int argc, char *argv[]) {
        const std::string text = "The quick brown fox jumps over the lazy dog";
        const std::regex vowels("[aeiou]");
    
        std::stringstream result;
        std::regex_replace(std::ostream_iterator<char>(result), text.begin(), text.end(), vowels, "");
    
        std::cout << result.str();  
    }
    

    输出是

    Th qck brwn fx jmps vr th lzy dg

    我认为这很简单。这个程序删除每个元音,或者更确切地说,用空字符串替换每个元音。您应该能够轻松地根据自己的需要对其进行自定义。如果您有任何其他问题,请发表评论。

    编辑:要将正则表达式转换为白名单,只需将其替换为其反转,[^aeiou]。那么结果会是

    euioouoeeao

    因为每个不是元音的字符都被空字符串替换了。

    【讨论】:

    • 谢谢!如果我只想允许确切的单词:“Hello”和单词:“World”怎么办?并删除其他所有内容?谢谢
    【解决方案2】:
    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main()
    {
    
        string str = "The quiock brown fox jumps over the lazy dog";
    
        regex vowels("a|e|i|o|u");
    
        str = regex_replace(str, vowels, "");
    
        cout << str << "\n";
    
        return 0;
    }
    

    【讨论】:

    • 永远不要使用bits/stdc++using namespace std,并放弃任何说要使用它们的资源。
    猜你喜欢
    • 2016-04-03
    • 2022-08-15
    • 2011-09-03
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    相关资源
    最近更新 更多