Search code examples
regexqregexp

Regular Expression to match an exact word with any number of spaces before and after it


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*"));

Solution

  • 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).