legami
legami

Reputation: 1373

Parse and remove part of a QString

I want to parse some kind (or pure) XML code from a QString.

My QString is like:

<a>cat</a>My cat is very nice.

I want to obtain 2 strings:

cat, and My Cat is very nice.

I think a XML parser is not maybe necessary, but in the future I will have more tags in the same string so it's also a very interesting point.

Upvotes: 2

Views: 5840

Answers (2)

Patrice Bernassola
Patrice Bernassola

Reputation: 14426

In Qt you have the QRegExp class that can help you to parse your QString.

According to Documentation example:

 QRegExp rxlen("^<a>(.*)</a>(.*)$");
 int pos = rxlen.indexIn("<a>cat</a>My cat is very nice.");
 QStringList list
 if (pos > -1) {
     list << = rxlen.cap(1); // "cat"
     list << = rxlen.cap(2); // "My cat is very nice."
 }

The QStringList list will contain the cat and My cat is very nice.

Upvotes: 6

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99565

You could use a regular expression <a>(.*)</a>(.*).

If you use Boost you could implement it like follows:

boost::regex exrp( "^<a>(.*)</a>(.*)$" );
boost::match_results<string::const_iterator> what;
if( regex_search( input_string, what, exrp ) ) {
    std::string tag( what[1].first, what[1].second );
    std::string value( what[2].first, what[2].second );
}

Upvotes: 3

Related Questions