【发布时间】:2015-03-10 12:30:17
【问题描述】:
我想用 C++ 删除或替换任何不包含在正则表达式中的字符。 例如,如果表达式为:[a-z] 且字符串为:“Hello-World”,则返回字符串将为:“Hello World”,因为只允许使用 a-z。
谢谢
【问题讨论】:
我想用 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
因为每个不是元音的字符都被空字符串替换了。
【讨论】:
#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,并放弃任何说要使用它们的资源。