在c++中使用正则表达式匹配来确定是否为二进制
using regex matching in c++ to determine if binary
我试图在c++中使用正则表达式来确定字符串是否只包含二进制(1/0)。我在java中使用。matches("[01]+")非常简单地做到了这一点。然而,现在当我试图转换到c++我有问题
我正在使用Visual studio 2010并得到这个错误
错误:没有重载函数"regex_match"的实例匹配参数列表
我的代码
#include <iostream>
#include <string>
#include <regex>
using namespace std;
// ...
string bFU;
do
{
cout << "nEnter a binary value containing up to 16 digits: ";
getline (cin, bFU);
if (!regex_match(bFU, "[01]+") || bFU.length()>16)
{
cout << "nError: Invalid binary value.nTry again.n"
"Press Enter to continue ... ";
bFU = "a";
cin.ignore(80, 'n');
}
} while (!regex_match(bFU, "[01]+"));
在visual studio中,当我将鼠标移到regex_match(红色下划线)上时,会出现这个错误
谢谢你的帮助,我一直在谷歌和分类通过几十个网站,它只是使问题更加模糊
regex_match
接受一个std::basic_regex
而不是一个字符串作为正则表达式。
如果您检查regex_match
的引用,您将看到您传递的参数与函数实际使用的参数不匹配。
参见参考资料中的示例,了解如何使用regex_match
函数。
我将如何编写您的程序:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
const basic_regex<char> binmatcher("[01]+");
string bFU;
for (bool matched = false; !matched;)
{
cout << "nEnter a binary value containing up to 16 digits: ";
getline(cin, bFU);
matched = regex_match(bFU, binmatcher);
if (!matched || bFU.length()>16)
{
cout << "nError: Invalid binary value.nTry again.n"
"Press Enter to continue ... ";
cin.ignore(80, 'n');
}
}
cout << "The binary value I found acceptable was: " << bFU << 'n';
return 0;
}
不幸的是,我无法真正测试这个,因为在g++ 4.7.2中不支持正则表达式。
您注意到,regex_match
不接受字符串。也不应该。编译正则表达式通常比使用正则表达式的计算强度大得多。
Perl之所以如此之快,是因为它在第一次遇到正则表达式时就编译它们,这是一个对您隐藏的步骤,在某些情况下(例如在运行时生成表达式时)会导致令人惊讶的结果。
这是::std::regex_match
的文档。在这种情况下,您想要的重载是重载6,它接受一个::std::string
和一个::std::basic_regex
作为参数。
相关文章:
- FlatBuffers/Protobuf 中是否有支持任意 24 位有符号整数定义的可移植二进制序列化架构?
- 测试树是否为二进制搜索树
- 如果使用非公共类,vtable 是否会在二进制文件中持续存在?
- 是否可以在一个循环中写入多个二进制文件
- 添加noexcept是否会破坏二进制兼容性
- 如何检查二进制文件中是否存在字符串
- 在Qt中使用C++Lambda函数作为插槽是否有助于保持库的二进制兼容性?
- 模板函数中的无捕获 lambda 是否具有多个二进制实现?
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何检查LLDB是否可以连接到二进制
- 是否有针对跳跃二进制搜索的直观解释
- 模板类静态在最终二进制文件中跨共享库以不同方式实例化是否一致
- 如果在执行过程中替换二进制文件,"const"数组是否驻留在内存中?
- 是否有一种跨平台的方法可以在使用 C++ 编写的二进制应用程序中嵌入资源?
- 将二进制字节 (char*) 转换为 uint64_t*,是否安全
- 检查节点是否是二进制搜索树的根
- 浮点数的二进制相等比较是否正确
- 将敏感数据存储在C 编译的二进制文件中是否安全
- 检查二进制文件中是否使用了提升