regex_match找不到方括号
regex_match fails to find square brackets
我正在尝试对一个包含方括号([...]
)的字符串执行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小提琴,编译器不应该成为问题即使在那里,我也没有看到regex_match发生
您遇到的主要问题是过时的gcc编译器:您需要升级到最新版本。4.8.x只是不支持regex。
现在,您应该使用的代码是:
#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演示
使用
regex_search
而不是regex_match
来搜索部分匹配(regex_match
需要完整字符串匹配)- 正则表达式模式中的
[2]
与文字2
匹配([...]
是与字符类中指定的范围/列表中的1个字符匹配的字符类)。要匹配文本方括号,您需要转义[
,而不必转义]
:R"(a/b/c[2]/d)"
它们肯定应该使用反斜杠进行转义。不幸的是,由于反斜杠本身在文字字符串中是特殊的,所以需要两个反斜杠。因此regex应该看起来像"(.*)a/b/c\[2\]/d(.*)"
。
原始字符串文字通常会简化必须具有复杂转义序列的情况:
#include <iostream>
#include <cstring>
#include <regex>
using namespace std;
int main () {
std::string str1 = "a/b/c[2]/d";
std::string str2 = R"regex((.*)a/b/c[2]/d(.*))regex";
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;
}
}
预期输出:
str1 = a/b/c[2]/d
str2 = (.*)a/b/c[2]/d(.*)
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 找不到QtResource文件中的文件
- VC++本机单元测试,找不到调试符号
- RegGetValue在当前用户下找不到名称
- 带有 -stdlib=libc++ 的 clang++ 9.0.1 找不到<optional>
- c++找不到具有相同哈希的无序集合元素
- 找不到以下加速库:boost_fiber
- 找不到 FLTK(缺少:FLTK_INCLUDE_DIR)
- 设置 Visual Studio for MPI: 找不到标识符错误
- "assimp/config.h"找不到,但它在文件夹中
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- C++系统找不到指定的文件错误
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- vcpkg 添加新库,但找不到
- Qt 5.11.2 (Clang 8.0 (Apple), 64 位), 找不到 QJSEngine 文件
- regex_match找不到方括号