gpt4 book ai didi

c++ - 无法匹配普通的正则表达式

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

我正在学习如何在 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).

最佳答案

我不认为这是 \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();
}

关于c++ - 无法匹配普通的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339948/

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