Question

I am developing an application using Qt/KDE. While writing code for this, I need to read a QString that contains values like ( ; delimited)

<http://example.com/example.ext.torrent>; rel=describedby; type="application/x-bittorrent"; name="differentname.ext"

I need to read every attribute like rel, type and name into a different QString. The apporach I have taken so far is something like this

if (line.contains("describedby")) {
        m_reltype = "describedby" ;
    }
    if (line.contains("duplicate")) {
        m_reltype = "duplicate";
    }

That is if I need to be bothered only by the presence of an attribute (and not its value) I am manually looking for the text and setting if the attribute is present. This approach however fails for attributes like "type" and name whose actual values need to be stored in a QString. Although I know this can be done by splitting the entire string at the delimiter ; and then searching for the attribute or its value, I wanted to know is there a cleaner and a more efficient way of doing it.

Was it helpful?

Solution

As I understand, the data is not always an URL. So,

1: Split the string

2: For each substring, separate the identifier from the value:

id = str.mid(0,str.indexOf("="));
value = str.mid(str.indexOf("=")+1);

You can also use a RegExp:

regexp = "^([a-z]+)\s*=\s*(.*)$";
id = \1 of the regexp;
value = \2 of the regexp;

OTHER TIPS

I need to read every attribute like rel, type and name into a different QString.

Is there a gurantee that this string will always be a URL?

I wanted to know is there a cleaner and a more efficient way of doing it.

Don't reinvent the wheel! You can use QURL::queryItems which would parse these query variables and return a map of name-value pairs.

However, make sure that your string is a well-formed URL (so that QURL does not reject it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top