0

我想从文本文件中获取一些字符串。我知道如何获取文本文件的整个字符串

QTextStream Stream (GEO); 
QString text;    
 do    
{    
text = Stream.readLine();  

}
while(!text.isNull());

这可以很好地获取 QString 文本下的所有文本,但我只需要文本中的一些特定字符串,示意图如下:

if the text "start" appears in the Qstring text (or the QTextStream Stream) 

save the following text under QString First

until the text "end" appears

有人可以告诉我如何做到这一点,或者甚至可以给我一个小例子吗?

4

1 回答 1

1

您可以使用的一件事是使用 indexOf() 获取“开始”和“结束”的索引,然后直接使用:

QString x = "start some text here end";
QString s = "start";
QString e = "end"
int start = x.indexOf(s, 0, Qt::CaseInsensitive);  // returns the first encounter of the string 
int end = x.indexOf(e, Qt::CaseInsensitive);  // returns 21

if(start != -1) // we found it
    QString y = x.mid(start + s.length(), end);

或 midRef 如果您不想创建新列表。您可能还必须处理“结束”,否则您可能会从 0 变为 -1,这不会返回任何内容。也许(结束>开始?结束:开始)

编辑:没关系。如果 end == -1 这意味着它将返回所有内容直到结束(默认情况下,第二个参数是 -1)。如果您不想要这个,您可以使用我的示例,并在选择“结束”时使用某种 if 语句

编辑:注意到我错过了文档,这将定义。工作:

#include <QDebug>

int main(int argc, char *argv[]) {
    QString x = "start some text here end";
    QString s = "start";
    QString e = "end";
    int start = x.indexOf(s, 0, Qt::CaseInsensitive); 
    int end = x.indexOf(e, Qt::CaseInsensitive); 

    if(start != -1){ // we found it
        QString y = x.mid(start + s.length(), ((end - (start + s.length())) > -1 ? (end - (start + s.length())) : -1)); // if you dont wanna pass in a number less than -1
        or
        QString y = x.mid(start + s.length(), (end - (start + s.length()))); // should not be any issues passing in a number less than -1, still works

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

这会产生以下结果。最后两个数字是“开始”结束和“结束”开始的地方。

x = "这里开始一些文字结束" => "这里一些文字" 5 16

x = " some text here end" => 没有输出

x =“测试开始在这里开始一些文字结束”=>“在这里开始一些文字”13 22

x = "测试开始在这里开始一些文本" => "在这里开始一些文本" 13 -14

或者您可以使用正则表达式来完成。在这里为您写了一个非常简单的片段:

#include <QDebug>
#include <QRegExp>

int main(int argc, char *argv[]) {
    QRegExp rxlen("(start)(.*(?=$|end))");
    rxlen.setMinimal(true); // it's lazy which means that if it finds "end" it stops and not trying to find "$" which is the end of the string 
    int pos = rxlen.indexIn("test start testing some text start here fdsfdsfdsend test ");

    if (pos > -1) { // if the string matched, which means that "start" will be in it, followed by a string 
        qDebug() <<  rxlen.cap(2); // " testing some text start here fdsfdsfds" 
    }
}

This works even if you done have "end" in the end, then it just parse to the end of the line. Enjoy!

于 2012-03-01T20:50:53.680 回答