我想将变量从函数传递到我正在调用的主作用域,我正在尝试像在C中那样做,但它什么都不返回。
我希望能够在功能返回后输出并处理它
#include "StdAfx.h"
#include <regex>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
std::tr1::match_results<std::string::const_iterator> match(std::string& regex, const std::string& ip,std::tr1::match_results<std::string::const_iterator> res)
{
const std::tr1::regex pattern(regex.c_str());
bool valid = std::tr1::regex_match(ip, res, pattern);
std::cout << ip << " t: " << (valid ? "valid" : "invalid") << std::endl;
cout << "FIRST RES FOUND: " << res[1] << endl;
return res;
}
int main()
{
string regex = "(\d{1,3}):(\d{1,3}):(\d{1,3}):(\d{1,3})";
string ip = "49:22:33:444";
std::tr1::match_results<std::string::const_iterator> res;
match(regex,ip.c_str(), res);
cout << "Result >" << res[1] << "< " << endl;
_getch(); return 0;
}
当我编译并运行时,输出为:"FIRST RES FOUND:49结果><"
这可能是一个非常简单的解决方案,但我必须做些什么才能为我的main设置它?可以正确地读取它,如:"Result>49<"
提前感谢。:)
选项1:使用引用:
void match(string& regex, const string& ip, tr1::match_results<string::const_iterator> & res)
{
const tr1::regex pattern(regex.c_str());
bool valid = tr1::regex_match(ip, res, pattern);
cout << ip << " t: " << (valid ? "valid" : "invalid") << endl;
cout << "FIRST RES FOUND: " << res[1] << endl;
}
选项2:按值返回结果并存储:
tr1::match_results<string::const_iterator> match(string& regex, const string& ip)
{
tr1::match_results<string::const_iterator> res;
// ...
return res;
}
int main()
{
// ...
tr1::match_results<string::const_iterator> res = match(regex, ip);
}
另外,绝对不需要所有的c_str()
调用,因为<regex>
有一个功能完美的std::string
接口。查看文档以了解详细信息,您只需要正确输入几个类型名称即可。
编辑:以下是使用std::string
的一些基本示例。std::wstring
、char*
和wchar_t*
有等价结构,但std::string
s应该是最有用的。
由于<regex>
的支持仍然参差不齐,您也应该考虑TR1和Boost的替代方案;我提供所有三种,你可以选择一种:
namespace ns = std; // for <regex>
namespace ns = std::tr1; // for <tr1/regex>
namespace ns = boost; // for <boost/regex.hpp>
ns::regex r("");
ns::smatch rxres; // 's' for 'string'
std::string data = argv[1]; // the data to be matched
// Fun #1: Search once
if (!ns::regex_search(data, rxres, r))
{
std::cout << "No match." << std::endl;
return 0;
}
// Fun #2: Iterate over all matches
ns::sregex_iterator rt(data.begin(), data.end(), r), rend;
for ( ; rt != rend; ++rt)
{
// *rt is the entire match object
for (auto it = rt->begin(), end = rt->end(); it != end; ++it)
{
// *it is the current capture group; the first one is the entire match
std::cout << " Match[" << std::distance(rt->begin(), it) << "]: " << *it << ", length " << it->length() << std::endl;
}
}
不要忘记处理类型为ns::regex_error
的异常。
通过引用而不是通过值传递res
。换句话说,将参数res
声明为引用,而不是值,即type &res
,而不是type res
。