我遇到了 C++ 正则表达式的问题。
我有一个像“f 123/123 1234/123/124 12”这样的字符串,我想得到“/”之前的所有数字。
这是我的正则表达式:
"\s(\d+)".
我在 http://rubular.com/ 上试过了它有效。 这是我的代码:
std::regex rgx("\\s(\\d+)");
std::smatch match;
if (std::regex_search(line, match, rgx))
{
std::cout << "Match\n";
std::string *msg = new std::string();
std::cout << "match[0]:" << match[0] << "\n";
std::cout << "match[1]:" << match[1] << "\n";
std::cout << "match[2]:" << match[2] << "\n";
}
但是我明白了:
Match
match[0]:123
match[1]:123
match[2]:
我意识到 match[0]
不是 Python 和 Ruby 中的“组”。
最佳答案
regex_search
匹配一次(匹配正则表达式的第一个子字符串)。你需要循环。
尝试以下操作:
std::regex rgx("\\s(\\d+)");
std::smatch match;
while (std::regex_search(line, match, rgx))
{
std::cout << match[0] << std::endl;
line = match.suffix().str();
}
关于c++ - 如何使用正则表达式 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658860/