Search code examples
qtg-code

How to isolate an integer in a QString


I have a QString of Gcode that will look like this:

T<some number> <and anything might come after it>

Currently, I'm using myString.midRef(1,1).toInt() to get the digit I want (I don't care about the rest of the line). However, this will not work if there is a two digit number, like so:

T12 ;blah blah blah

Is there a good / better way of doing this other than searching index by index to see where the number stops?

  • There will always be a T in front of the number.
  • There will always be a semicolon after the number if there is any other text after it, but there may not be a space in between the number and the semicolon.
  • There may or may not be anything after the number at all.

Solution

  • Use regular expression to extract the number pattern, e.g.

    int ib, ie, n;
    QStringRef num;
    ib = str.indexOf(QRegExp("T\\d+(\\s*;{1}.|$)"));
    if (ib >= 0) {
        ib++;
        ie = str.indexOf(";", ib);
        n = ie >= ib ? ie - ib : -1; 
        num = str.midRef(ib, n);
    }
    

    Notes:

    1. T\d+ match a pattern begins with T followed by one or more digit.
    2. \s*;{1}.|$ match zero or more white spaces followed by semicolon plus any character OR exactly none in the last character.

    Please note that in the above rule, "T123 " or "T123\n" won't match the pattern. If you want to allow white space, use the following:

    QRegExp("T\\d+\\s*(;{1}.|$)")