gpt4 book ai didi

c++ - 在 C++ 中使用正则表达式读取空格、换行符和制表符

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:48 25 4
gpt4 key购买 nike

我正在 try catch 空格 \s、行尾 '\n''\r'、制表符 '\t',但没有成功。

这是我尝试过的:

#include <iostream>
#include <regex>

int main()
{
std::regex s ("\\s(.*)");
std::regex n ("\\n(.*)");
std::regex r ("\\r(.*)");
std::regex t ("\\t(.*)");
const char str[]=" subject \rsubject \nsubject \tsubject";
std::cmatch cmS;
std::cmatch cmN;
std::cmatch cmR;
std::cmatch cmT;
if (std::regex_match (str, cmS,s))
for (unsigned i=0; i<cmS.size(); ++i) {
std::cout << "[" << cmS[i] << "] ";
}
if (std::regex_match (str, cmN,n))
for (unsigned i=0; i<cmN.size(); ++i) {
std::cout << "[" << cmN[i] << "] ";
}
if (std::regex_match (str, cmR,r))
for (unsigned i=0; i<cmR.size(); ++i) {
std::cout << "[" << cmR[i] << "] ";
}

if (std::regex_match (str, cmT,t))
for (unsigned i=0; i<cmT.size(); ++i) {
std::cout << "[" << cmT[i] << "] ";
}

return 0;
}

我也这样试过,但也没有成功,我的程序崩溃了:

if (std::regex_match ("subject subject", std::regex("\\s(sub)"),std::regex_constants::ECMAScript ))
std::cout << "string literal matched\n";

if (std::regex_match ("subject subject", std::regex("\s(sub)"),std::regex_constants::ECMAScript ))
std::cout << "string literal matched\n";

if (std::regex_match ("subject subject", std::regex("[[:s:]](sub)"),std::regex_constants::ECMAScript ))
std::cout << "string literal matched\n";

我知道有一些外部类,如 boost 可以在 C++ 中执行 regex,但我的目标是不为我的程序使用任何外部类和依赖项,所以我需要在 C++ 本身内部执行此操作。

最佳答案

要启用正则表达式,您需要安装 GCC 4.9.0 或更高版本,因为在以前的编译版本中正则表达式模块不起作用。

接下来,您需要使用 regex_search 而不是 regex_match,因为后者需要完整的字符串匹配,而您正在寻找子字符串。

参见regex_match说明:

The entire target sequence must match the regular expression for this function to return true (i.e., without any additional characters before or after the match). For a function that returns true when the match is only part of the sequence, see regex_search.

关于c++ - 在 C++ 中使用正则表达式读取空格、换行符和制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com