我想用 C++ 删除或替换正则表达式中未包含的任何字符。 例如,如果表达式为:[a-z],字符串为:“Hello-World”,则返回字符串将为:“Hello World”,因为只允许使用 a-z。
谢谢
最佳答案
下面是一个示例程序,它使用 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
因为每个非元音的字符都被替换为空字符串。
关于c++ - 使用 C++ 替换或删除正则表达式中不存在的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28963810/