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

标签 c++ regex

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

相关文章:

c++ - 如何使模板仅通过第一个参数解析类型?

c++ - 如何检查成员函数或自由函数是否适用于确切的给定类型(而不是其任何基类)?

c# - Visual Studio 格式文档——如何用 C# 编写

regex - 如何使用正则表达式删除未知数量的换行符

C++ 指向不在范围内的函数调用的指针

c++ - C++ 中 priority_queue 的奇怪的用户定义比较结构错误

c++ - 我可以从 C++ 程序中调用 Objective-C 类吗?

c# - 字符串中的子字符串值

javascript - 如何在javascript中用空格替换unicode字符u00A0?

php - preg_match 多个单词