为什么我的正则表达式工作 JavaScript 而不是在 C++ 中?
Why does my regex work JavaScript but not in C++?
我的正则表达式应该捕获所有函数声明的名称:
([\w{1}][\w_]+)(?=\(.+{)
在 JavaScript 中它按预期工作:
'int main() {\r\nfunctionCall();\r\nfunctionDeclaration() {}\r\n}'.match(/([\w{1}][\w_]+)(?=\(.+{)/g);
// [ 'main', 'functionDeclaration' ]
在 C++ Builder 中我得到这个错误:
regex_error(error_badrepeat): One of *?+{ was not preceded by a valid
regular expression.
最小可重现示例:
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> matches;
string text = "int main() {\r\nfunctionCall();\r\nfunctionDeclaration() {}\r\n}";
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 不同。
我的正则表达式应该捕获所有函数声明的名称:
([\w{1}][\w_]+)(?=\(.+{)
在 JavaScript 中它按预期工作:
'int main() {\r\nfunctionCall();\r\nfunctionDeclaration() {}\r\n}'.match(/([\w{1}][\w_]+)(?=\(.+{)/g);
// [ 'main', 'functionDeclaration' ]
在 C++ Builder 中我得到这个错误:
regex_error(error_badrepeat): One of *?+{ was not preceded by a valid regular expression.
最小可重现示例:
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> matches;
string text = "int main() {\r\nfunctionCall();\r\nfunctionDeclaration() {}\r\n}";
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 不同。