c++ - 正则表达式迭代器在 Cpp 中不起作用

标签 c++ regex windows visual-studio-2010

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

我正在尝试使用以下代码提取 tracert 的 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 our pint 一样?另一个可以像 arp -a 一样获取 mac 地址)

最佳答案

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

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

请注意:

  • 不假设空格是空格而不是制表符
  • 不假定行首的精确间距
  • 确实要求在 1 字符后至少有 1 个空格(因此它不会匹配以 13 开头的行,例如)
  • 如果可能的话使用非贪婪匹配
#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

关于c++ - 正则表达式迭代器在 Cpp 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138813/

相关文章:

c++ - 无法用代码 1 编译程序退出

python - python中多次出现的正则表达式

javascript - 如何避免使用正则表达式将 unicode 重音符后的字母大写

c++ - 如何将当前进程分配给新创建的作业对象?

c++ - FPU,SSE 单 float 。哪个更快?低于或高于

c++ - 使用通用 setter 设置数据成员

c++ - 中间目标文件抛出的对函数 c++ 的 undefined reference

regex - 我怎样才能让它只匹配单词 'speaks' 之后的单词并忽略逗号和空格

windows - 将 Sitecore PowerShell 扩展与 native PowerShell 结合使用

java - 运行多个 Java 版本