1

我在 Visual Studio 2010 上使用 C++(我不认为它的 v11 标准,但我没有检查)。

我正在尝试使用以下代码提取跟踪器的 IP 地址:

#include <iomanip>
#include <iostream>
#include <string>
#include <regex>

using namespace std;
typedef regex_iterator<string::iterator> regexp;
#define MAX_BUFFER 255
int main() {
    string out;
    char buffer[MAX_BUFFER];
    smatch m;
    regex e("  1.+\\[(.+)\\]");
    FILE *stream = _popen("tracert SOMEHOSTNAME", "r");
    while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) {
        out = buffer;
        regexp rit (out.begin(), out.end(), e);
        regexp rend;
        while (rit != rend) {
            cout << rit->str() << endl;
            ++rit;
        }
    }
    _pclose(stream);
    cout << "Done.";
    cin >> buffer;
}

但是,正则表达式并没有提取组本身。相反,它只是吐出整条线!

我以为我非常仔细地遵循示例,但似乎我没有正确使用 regex_iterator。

1 - 我怎样才能最好地从这个字符串中提取 IP

(附带问题 - 是否有一个 C++ 函数将进入网络并从主机名获取 IP,就像 tracert 我们的 pint 一样?另一个会像 arp -a 一样获取 mac 地址)

4

1 回答 1

3

我没有 MSVC,而且 GNU 已经破坏了对 std::regex 的支持,所以我在这里玩了 `boost::regex':

regex e("^\\s*1\\s.*?\\[(.*?)\\]");

请注意:

  • 不假设空格是空格而不是制表符
  • 不假定行首的确切间距
  • 确实要求字符后至少有 1 个空格1(因此它与以 开头的行不匹配13,例如)
  • if 尽可能使用非贪婪匹配
#include <iostream>
#include <string>
#include <boost/regex.hpp>

using namespace std;
using boost::regex;
using boost::regex_iterator;
#define MAX_BUFFER 255

int main()
{
    char buffer[MAX_BUFFER];
    regex e("^\\s*1\\s.*?\\[(.*?)\\]");

    FILE *stream = popen("cat input.txt", "r");
    while(fgets(buffer, MAX_BUFFER, stream) != NULL)
    {
        typedef regex_iterator<string::iterator> regit;

        string out = buffer;
        regit rit(out.begin(), out.end(), e);
        regit rend;
        while(rit != rend)
        {
            cout << (*rit)[1].str() << endl;
            ++rit;
        }
    }
    pclose(stream);
    cout << "Done.\n";
}

这似乎适用于input.txt

Tracing route to 11.1.0.1 over a maximum of 30 hops

1     2 ms     3 ms     2 ms  [157.54.48.1]
2    75 ms    83 ms    88 ms  [11.1.0.67]
3    73 ms    79 ms    93 ms  [11.1.0.1]

Trace complete.

印刷:

157.54.48.1
于 2013-08-09T01:46:04.743 回答