无法匹配琐碎的正则表达式

时间:2018-01-19 11:19:59

标签: c++ regex c++11

我正在学习如何在C ++中使用正则表达式库。我实施了http://www.cplusplus.com/reference/regex/regex_match/

中的示例
std::string s( "subject" );
std::regex e( "(sub)(.*)" );

std::smatch sm;  
std::regex_match( s, sm, e );
std::cout << "string object with " << sm.size() << " matches\n";

打印

string object with 3 matches

正如所料。但是,如果我将第一行更改为

std::string s( "Hello world!" );
std::regex e( "\\S+" );

我得到了

string object with 0 matches

我错过了一些明显的东西,或者这是一个错误?我使用的是gcc 5.4.0。 (g ++ --std = c ++ 11)。

2 个答案:

答案 0 :(得分:3)

我认为\S存在问题,但regex_match必须与整个字符串匹配,否则根本不匹配。

尝试用这个替换前两行:

std::string s( "Hello world!" );
std::regex e( "\\S+ \\S+" );

如果您想匹配子字符串,请尝试regex_search

std::string s( "Hello world!" );
std::regex e( "\\S+" );

std::smatch sm;

// Loop through matches
while (std::regex_search( s, sm, e )) {
    std::cout << "string object with " << sm.size() << " matches\n";
    // Replace current string with the remainder, otherwise this
    // will loop infinitely
    s = sm.suffix().str();
}

答案 1 :(得分:-1)

C ++标准有很多选项可以传递给regex构造函数。有关选项,请参阅here。其中一些指定使用哪种语法。试试支持\S的{​​{3}}。

类似的东西:

std::regex e( "(sub)(.*)", std::regex::ECMAScript );

例如,扩展语法不支持\S。我不清楚哪一个是默认值,但值得一试,看它是否与ECMAScript不同。