在c++中使用正则表达式匹配来确定是否为二进制

using regex matching in c++ to determine if binary

本文关键字:是否 二进制 c++ 正则表达式      更新时间:2023-10-16

我试图在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作为参数。