boost::xpressive::placeholder — 用于定义一个占位符,以代表用于语义操作的变量。
// In header: <boost/xpressive/xpressive_fwd.hpp> template<typename T, int I = 0> struct placeholder { // public member functions unspecified operator=(T &) const; unspecified operator=(T const &) const; };
使用 placeholder<>
定义一个占位符,用于语义操作中代表真实对象。占位符的使用允许一次定义带有操作的正则表达式,并在许多上下文中重用,以便在定义正则表达式时不可用的对象进行读写。
您可以通过创建 placeholder<T>
类型的对象,并在语义操作中使用该对象,就像您打算使用 T
类型对象一样,来使用 placeholder<>
。
placeholder<int> _i; placeholder<double> _d; sregex rex = ( some >> regex >> here ) [ ++_i, _d *= _d ];
然后,在进行模式匹配时,无论是使用 regex_search()
、regex_match()
还是 regex_replace()
,请传递一个 match_results<>
对象,该对象包含用于正则表达式对象语义操作中使用的占位符的绑定。您可以通过调用 match_results::let
来创建绑定,如下所示:
int i = 0; double d = 3.14; smatch what; what.let(_i = i) .let(_d = d); if(regex_match("some string", rex, what)) // i and d mutated here
如果执行的语义操作包含未绑定的占位符,则会抛出 regex_error
类型的异常。
有关更多信息,请参阅 xpressive::let()
的讨论以及用户指南中“引用非局部变量”部分。
示例
// Define a placeholder for a map object: placeholder<std::map<std::string, int> > _map; // Match a word and an integer, separated by =>, // and then stuff the result into a std::map<> sregex pair = ( (s1= +_w) >> "=>" >> (s2= +_d) ) [ _map[s1] = as<int>(s2) ]; // Match one or more word/integer pairs, separated // by whitespace. sregex rx = pair >> *(+_s >> pair); // The string to parse std::string str("aaa=>1 bbb=>23 ccc=>456"); // Here is the actual map to fill in: std::map<std::string, int> result; // Bind the _map placeholder to the actual map smatch what; what.let( _map = result ); // Execute the match and fill in result map if(regex_match(str, what, rx)) { std::cout << result["aaa"] << '\n'; std::cout << result["bbb"] << '\n'; std::cout << result["ccc"] << '\n'; }