我正在尝试对内部有方括号( [...]
)的字符串进行 regex_match 。
到目前为止我尝试过的事情:
- 正常匹配
- 用 1 个斜杠反斜杠方括号
- 用 2 个斜杠反斜杠方括号
重现代码:
#include <iostream>
#include <cstring>
#include <regex>
using namespace std;
int main () {
std::string str1 = "a/b/c[2]/d";
std::string str2 = "(.*)a/b/c[2]/d(.*)";
std::regex e(str2);
std::cout << "str1 = " << str1 << std::endl;
std::cout << "str2 = " << str2 << std::endl;
if (regex_match(str1, e)) {
std::cout << "matched" << std::endl;
}
}
这是我每次编译时收到的错误消息。
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error
Aborted (core dumped)
堆栈溢出成员告诉我,gcc 4.8 或更早版本已知存在错误。因此,我需要将其更新到最新版本。
我创建了一个Ideone fiddle编译器不应该出现问题的地方。 即使在那里,我也没有看到 regex_match 发生。
最佳答案
您遇到的主要问题是过时的 gcc 编译器:您需要升级到某个最新版本。 4.8.x 只是不支持正则表达式。
现在,您应该使用的代码是:
#include <iostream>
#include <cstring>
#include <regex>
using namespace std;
int main () {
std::string str1 = "a/b/c[2]/d";
std::string str2 = R"(a/b/c\[2]/d)";
std::regex e(str2);
std::cout << "str1 = " << str1 << std::endl;
std::cout << "str2 = " << str2 << std::endl;
if (regex_search(str1, e)) {
std::cout << "matched" << std::endl;
}
}
请参阅IDEONE demo
使用
regex_search
而不是regex_match
来搜索部分匹配(regex_match
需要完整字符串匹配)<- 正则表达式模式中的
[2]
与文字2
匹配([...]
是匹配 1 个字符的字符类字符类中指定的范围/列表)。要匹配文字方括号,您需要转义[
而不必转义]
:R"(a/b/c\[2 ]/d)"
。
关于c++ - regex_match 找不到方括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596563/