Comment spécifier la méthode qstring :: indexof de ne pas être sensible au nombre d'espaces entre deux mots?

StackOverflow https://stackoverflow.com//questions/9622918

  •  09-12-2019
  •  | 
  •  

Question

J'ai écrit un code source comme:

int main(int argc, char *argv[]) {
    QFile File (directory + "/File");

        if(File.open(QIODevice::ReadOnly | QIODevice::Text))
        {
         QTextStream Stream (&File);
         QString FileText;
           do
            {
      FileText = Stream.readLine();
    QString s = "start";
    QString e = "end   here";
    int start = FileText.indexOf(s, 0, Qt::CaseInsensitive); 
    int end = FileText.indexOf(e, Qt::CaseInsensitive); 

    if(start != -1){ // we found it

        QString y = FileText.mid(start + s.length(), (end - (start + s.length()))); 

        qDebug() << y << (start + s.length()) << (end - (start + s.length()));
    }

}

Mon problème ici est que l'int-fin= filetext.indexof (e, qt :: cassiq); Avec QString e = "end here"; est simplement trouvé quand il y a exactement trois espaces entre le mot "fin" et "ici".Ceci est problématique, car dans le texte, je lis les espaces entre ces deux mots différents diffèrent certainement de temps en temps.De plus, j'ai besoin d'écrire les deux mots "fin" et "ici".J'ai essayé de réduire le problème à la base et j'espère que quelqu'un a une idée / solution.

Était-ce utile?

La solution

Réduisez le nombre d'interspaces à 1 à l'aide de QString::simplified() Méthode.

Autres conseils

Vous pouvez également essayer qregexp :

#include <QDebug>
#include <QString>
#include <QRegExp>

int main()
{
    QString text("start ABCDE1234?!-: end  here foo bar");

    // create regular expression
    QRegExp rx("start\\s+(.+)\\s+end\\s+here", Qt::CaseInsensitive);

    int pos=0;

    // look for possible matches
    while ((pos=rx.indexIn(text, pos)) != -1) {
        qDebug() << rx.cap(1); // get first match in (.+)
        pos+=rx.matchedLength();
    }

    return 0;
}

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top