如何用正则表达式匹配复杂的字符串

时间:2020-07-22 03:02:34

标签: c++ regex

我是C ++的新手,正在使用正则表达式函数,但无法获得所需的结果

c ++代码:

#include <regex>

std::string str = "[game.exe+009E820C]+338";
std::smatch result;
std::regex pattern("\\[([^\\[\\]]+)\\]");

std::regex_match(str, result, pattern);

// no result
std::cout << result[1] << std::endl;

我熟悉javascript正则表达式,因此可以获得所需的值:

'[game.exe+009E820C]+338'.match(/\[([^\[\]]+)\]/)[1]   =>   game.exe+009E820C

我的c ++代码是否做错了什么

1 个答案:

答案 0 :(得分:3)

如果要访问捕获组,则regex_match API似乎需要与整个输入匹配的模式。另外,为避免陷入负字符类(包括方括号)的困扰,我建议改用Perl惰性点。将所有这些放在一起:

std::string str = "[game.exe+009E820C]+338";
std::smatch result;
std::regex pattern(".*\\[(.*?)\\].*");
std::regex_match(str, result, pattern);
std::cout << result[1] << std::endl;

此打印:

game.exe+009E820C