我正在 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/