我真的建议对这项工作使用正则表达式(boost regex 或 std::regex)。
正则表达式可能看起来像
std::regex re("^(\\.[EV]/).*?$"); // the first submatch is the part you are looking for
这里有一点精神,以防你真的需要它:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
typedef std::string::const_iterator It;
int main()
{
std::vector<std::string>elements;
std::string input =
".V/ER/12/FRG/45S/16JAN\n"
".E/45/SHAM/CAMP/2";
It first(input.begin()), last(input.end());
bool ok = qi::parse(first, last,
(
'.' > qi::char_("EV") > '/'
>> qi::omit [ *(qi::char_ - qi::eol) ]
) % qi::eol,
elements);
if (ok)
{
for (int i=0; i<elements.size(); ++i)
std::cout << elements[i] << std::endl;
} else
{
std::cerr << "Parse failed at '" << std::string(first, last) << std::endl;
}
}
这将输出
V
E
如果你想在那里显示'.E/',有很多方法,例如
bool ok = qi::parse(first, last,
(
(qi::char_('.') > qi::char_("EV") > qi::char_('/' )
>> qi::omit [ *(qi::char_ - qi::eol) ] )
) % qi::eol,
elements);
输出:
.V/
.E/
奖金
显示如何包含线的“尾部”,可能存储到地图中:
#include <map>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
namespace qi = boost::spirit::qi;
typedef std::string::const_iterator It;
int main()
{
typedef std::map<std::string, std::string> result_t;
// or use a list to allow duplicate keys:
// typedef std::list<std::pair<std::string, std::string> > result_t;
result_t mappings;
std::string input =
".V/ER/12/FRG/45S/16JAN\n"
".E/45/SHAM/CAMP/2";
It first(input.begin()), last(input.end());
bool ok = qi::parse(first, last, (
qi::raw [ '.' > qi::char_("EV") > '/' ]
> qi::raw [ *(qi::char_ - qi::eol) ]
) % qi::eol,
mappings);
if (ok)
{
for (result_t::const_iterator it=mappings.begin();
it!=mappings.end(); ++it)
{
std::cout << it->first << " maps to " << it->second << std::endl;
}
} else
{
std::cerr << "Parse failed at '" << std::string(first, last) << std::endl;
}
}
会输出
.E/ maps to 45/SHAM/CAMP/2
.V/ maps to ER/12/FRG/45S/16JAN