1

I want to find an exact word "SUBRECORD" with any number of spaces before and after it. I have tried:

\s*SUBRECORD\s*
[ ]*SUBRECORD[ ]*
(\s)*SUBRECORD(\s)*

but none of them work.

EDIT:

this is the snippet of code that's not working:

QStringList list;
list.append("RECORD \"DEFSTA\" \"Definition des Stations\"");
list.append("  STRING     (2)  \"Version\";");
list.append("  SUBRECORD   (2)  \"Nb de Stations\";");
list.append("    STRING    (30) \"Nom de la Station\";  ");
list.append("    INTEGER   (2)  \"Numero de la Station\";");
list.append("    INTEGER   (4)  \"Extra charge\";");
list.append("    STRING    (5)  \"Mnemonique Station\";");
list.append("    DUMMY     (1)  \"Réserve\";");
list.append("  ENDSUBRECORD;");
list.append("  SIGNATURE        \"Signature\" ;  ");
list.append("ENDRECORD;");

qDebug() << "LAST INDEX OF SUBRECORD:" << list.lastIndexOf(QRegExp("\\s*SUBRECORD\\s*"));
max
  • 2,627
  • 1
  • 24
  • 44

1 Answers1

2

Reason:

lastIndexOf(...) only returns the index if there is an exact match of the entire line. This is from the Qt docs:

int QStringList::lastIndexOf ( const QRegExp & rx, int from = -1 ) const

Returns the index position of the last exact match of rx in the list, searching backward from index position from. If from is -1 (the default), the search starts at the last item. Returns -1 if no item matched.

Because \s*SUBRECORD\s* does not match the line exactly, it does not count it as a match.


Solution:

Instead try: .*\\s+SUBRECORD\\s+.*

The extra .* matches anything extra at the beginning and end.

The \s+ ensures there is at least one space (thanks @T.V.) - also, the extra \ is to escape the backslash when inputting as a QString (thanks @MoKi).

bcorso
  • 45,608
  • 10
  • 63
  • 75
  • The solution you suggested would result in the index of `ENDSUBRECORD;` being return. – T.V. Nov 14 '13 at 03:36
  • Thanks, I changed it to \s+ so that it looks for at least one space character – bcorso Nov 14 '13 at 03:38
  • 1
    the correct form would be to use double escape characters that is `.*\\s+SUBRECORD\\s+.*` since Qt accepts `QString` as the `QRegExp` constructor's argument. and yes you are right about it matching the whole line. – max Nov 14 '13 at 04:28