我在 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/