Como especificar o método QString::indexOf para não ser sensível ao número de espaços entre duas palavras?
Pergunta
Eu escrevi um código-fonte como:
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()));
}
}
Meu problema aqui é que int end = FileText.indexOf(e, Qt::CaseInsensitive);com QString e = "end here";
só é encontrado quando há exatamente três espaços entre a palavra "fim" e "aqui".Isto é problemático, porque no texto que li os espaços entre estas duas palavras certamente serão diferentes de tempos em tempos.Além disso, preciso escrever as palavras “fim” e “aqui”.Tentei reduzir o problema à base e espero que alguém tenha uma ideia/solução.
Solução
Reduza o número de espaços entre espaços para 1 usando QString::simplified()
método.
Outras dicas
Você também pode tentar 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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow