gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
使用c++写出匹配一个或多个非空格、非字母、非数字的字符
- User
使用c++写出匹配一个或多个非空格、非字母、非数字的字符
- Assistant
在C++中,你可以使用正则表达式(regular expressions, regex)来匹配符合你条件的字符。C++11及其之后的标准库中提供了正则表达式的支持。下面是一个示例程序,展示如何使用正则表达式匹配一个或多个非空格、非字母、非数字的字符:
cpp#include <iostream> #include <regex> #include <string> int main() { // 要匹配的字符串 std::string input = "Example string with special characters like @@, ** and ##!"; // 定义正则表达式 std::regex special_chars_regex(R"([^a-zA-Z0-9\s]+)"); // 查找匹配项 auto words_begin = std::sregex_iterator(input.begin(), input.end(), special_chars_regex); auto words_end = std::sregex_iterator(); std::cout << "Found " << std::distance(words_begin, words_end) << " matches:\n"; for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); std::cout << match_str << '\n'; } return 0; }