0

我正在尝试在一行中由“$”对分隔的一些字符串之间循环,用特定值替换每个匹配项,以便获得替换所有标记的输出行,但我被困在第二个匹配项上'不知道如何连接新的替换值:

const boost::regex expression( "\\$[\\w]+\\$" );
string fileLine( "Mr $SURNAME$ from $LOCATION$" );
string outLine;

string::const_iterator begin = fileLine.begin();
string::const_iterator end = fileLine.end();

boost::match_results<string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;

while ( regex_search( begin, end, what, expression, flags ) ) {
  actualValue = valuesMap[what[0]];

  ostringstream t( ios::out | ios::binary );
  ostream_iterator<char, char> oi( t );

  boost::regex_replace( oi, begin, end, expression, actualValue, 
                        boost::match_default | boost::format_first_only );
  outLine.append( t.str() );
  begin = what[0].second;
}

问题出在 outLine.append( t.str() ) 中,因为连接没有正确完成,因为在第一次匹配之后,outLine 已经保存了下一次匹配之前的一些字符。

4

2 回答 2

0

Though I'm not 100% sure about your intent, I presume your goal is replacing each matched substring in fileLine with the corresponding value of valuesMap.
If so, the following code might meet your purpose:

  ...same as your code...

  while ( regex_search( begin, end, what, expression, flags ) ) {
    outLine.insert( outLine.end(), begin, what[0].first );
    outLine += valuesMap[what[0]];
    begin = what[0].second;
  }

  outLine.insert( outLine.end(), begin, end );

Hope this helps

于 2011-03-15T21:39:17.327 回答
0

由于您仅请求替换字符串中的第一个值(通过使用boost::format_first_only标志)原始字符串

"Mr $SURNAME$ from $LOCATION$"

将被转换为

"Mr ACTUAL_VAL from $LOCATION$"

在第一次迭代然后

" from ACTUAL_VAL"

将被附加到它,因为您明确地将开始设置为“what[0].second。所以最终输出是

"Mr ACTUAL_VAL from $LOCATION$ from ACTUAL_VAL"

这不是你需要的。这是具有副作用的工作示例 - 它修改了 fileLine:

   const boost::regex expression( "\\$[\\w]+\\$" );
    string fileLine( "Mr $SURNAME$ from $LOCATION$" );
    string outLine;

    string::const_iterator begin = fileLine.begin();
    string::const_iterator end = fileLine.end();

    boost::match_results<string::const_iterator> what;
    boost::match_flag_type flags = boost::match_default;

    while ( regex_search( begin, end, what, expression, flags ) ) 
    {
        const char* actualValue = valuesMap[what[0]];

        ostringstream t( ios::out | ios::binary );
        ostream_iterator<char, char> oi( t );

        boost::regex_replace( oi, begin, end, expression, 
`enter code here`actualValue, boost::match_default | boost::format_first_only );

        fileLine.assign(t.str());
        begin = fileLine.begin();
        end = fileLine.end();        
    }

    std::cout << fileLine << std::endl;

如果你不想修改fileLine,那么你应该用“begin”和“end”来标记包含一个模式的滑动窗口的开始和结束。

于 2011-03-15T21:27:28.643 回答