为什么我的正则表达式可以用JavaScript,但不能用C++

Why does my regex work JavaScript but not in C++?

本文关键字:JavaScript 但不能 C++ 我的 正则表达式 为什么      更新时间:2024-05-09

我的正则表达式应该捕获所有函数声明的名称:

([w{1}][w_]+)(?=(.+{)

在JavaScript中,它按预期工作:

'int main() {rnfunctionCall();rnfunctionDeclaration() {}rn}'.match(/([w{1}][w_]+)(?=(.+{)/g);
// [ 'main', 'functionDeclaration' ]

在C++Builder中,我得到了这个错误:

regex_error(error_badrepeat(:*之一+{前面没有有效的正则表达式。

最小可复制性示例:

#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> matches;
string text = "int main() {rnfunctionCall();rnfunctionDeclaration() {}rn}";
try {
//regex myRegex("([\w{1}][\w_]+)(?=\()"); works as intended
regex myRegex("([\w{1}][\w_]+)(?=\(.+{)"); // throws error
sregex_iterator next(text.begin(), text.end(), myRegex);
sregex_iterator end;
while (next != end) {
smatch match = *next;
cout << match.str() << endl;
next++;
}
} catch (regex_error &e) {
cout << "([\w{1}][\w_]+)(?=\(.+{)"
<< "n"
<< e.what() << endl;
}
}

我用g++编译了上面的内容,而不是C++Builder,它给出的错误是不同的:Unexpected character in brace expression.

C++的正确正则表达式字符串文字是:

"([\w{1}][\w_]+)(?=\(.+\{)"

与JavaScript不同,{必须转义。

相关文章: