0

I am trying to parse a QString of this form:

QString str = "34 t:513 l:21 o:0x0147 [FBI] Miscellaneous No. : 89f2aad996ae4a5c961a 123 532af2";
QRegExp tagExp(":");
QStringList firstList = str.split(tagExp);

However I need only "9f2aad996ae4a5c961a 123 532af2". So is it possible to get the substring following ": "?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
goGud
  • 4,163
  • 11
  • 39
  • 63
  • I would split it like `str.split("No. :");` and take the second element in the list. – vahancho Apr 14 '16 at 13:34
  • 3
    It depends on the expected formats of the lines you want to parse. (e.g., is there always a “:”, and is the text before it random text or has it a structure). If it’s about the last “:”, I’d go for lastIndexOf(“:”) and QString::mid(). – Frank Osterfeld Apr 14 '16 at 13:53

1 Answers1

1

If I understand you correctly you want the last element of the list (after the last ":"). You can do the following:

QRegExp tagExp(":");
QStringList firstList = str.split(tagExp);
// Get the last string from list:
//  "34 t"
//  "513 l"
//  "21 o"
//  "0x0147 [FBI] Miscellaneous No. "
//  "89f2aad996ae4a5c961a 123 532af2"  <<-- this is the last element in list
QString requiredPart = firstList.takeLast();

The function takeLast gets the last string and returns it and also removes it from the list. If you don't want to remove the last element from the list you can do something like:

QString requiredPart = firstList.value(firstList.length() - 1);

or

QString requiredPart = firstList.at(firstList.length() - 1);

or

QString requiredPart = firstList[firstList.length() - 1];

But the first option is the safest as it covers you for "out of bounds" issues better.

You can also use:

requiredPart = requiredPart.trimmed();

to remove any spaces at the start / end. Or go further and use:

requiredPart = requiredPart.simplified();

To remove excess white-space within the string. You probably don't need this.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
code_fodder
  • 15,263
  • 17
  • 90
  • 167