简体   繁体   English

如何读取特定单词之间的文本文件?

[英]How to read text file between specific words?

I want the text between "profile name" and "###".The extracted text should be display in the text browser. 我想要“个人资料名称”和“ ###”之间的文本。提取的文本应显示在文本浏览器中。 The profile name is varying. 配置文件名称有所不同。 My text file(harnish_data.txt) is looking like this, 我的文本文件(harnish_data.txt)看起来像这样,

XYZ Profile
First Name :- XYZ
Second Name :- sssss
Last Name :- sssss

Favourite Food :- sssss
Favourite Actor :- sssss
Favourite Actress :- ssssss
###
PQR Profile
First Name :- PQR
Second Name :- hhhhh
Last Name :- hhhhh

Favourite Food :- hhhhhh
Favourite Actor :- hhhhhh
Favourite Actress :- hhhhh
###

Now If profile name is XYZ then I want the text data between XYZ Profile to ###. 现在,如果配置文件名称为XYZ,那么我希望XYZ配置文件之间的文本数据为###。 and If profile name is PQR then I want the text between PQR Profile to ###. 如果个人资料名称为PQR,则我希望PQR个人资料之间的文本为###。 The no of a profile maybe increase. 配置文件的数量可能会增加。

I have tried like this, here detail_data.txt file contains only my profile name. 我已经尝试过了,这里的detail_data.txt文件仅包含我的个人资料名称。

QFile file("detail_data.txt");
file.open(QIODevice::ReadWrite);
QTextStream inn(&file);
const QString contentt = inn.readLine(); //contentt contain profile name
qDebug() << contentt; // PQR

QFile MyFile("harnish_data.txt"); // contains profile data
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);
const QString content = in.readAll();  // contains profile data

QString srch (contentt + " " + "Profile");
qDebug() << srch << "search string"; // PQR Profile
int pos = content.indexOf(srch);
qDebug() << pos << "index of srch"; //155

if ( pos >= 0 )
{
    QString restOfLine = content.mid(pos + srch.length(), srch.endsWith("###"));
    qDebug() << srch.length() << "srch.length()"; //11
    qDebug() << restOfLine << "restOfLine of mid"; //\nFirst Name :- PQR\nSecond Name :- hhhhh\nLast Name :- hhhhh\n\nFavourite Food :- hhhhhh\nFavourite Actor :- hhhhhh\nFavourite Actress :- hhhhh\n###\n\n" restOfLine of mid
}
ui->textBrowser->setText(in.readAll());

I have run the above code but it gives me whole text file data while I want data between 'profile name' and '###'. 我已经运行了上面的代码,但是当我想要'profile name'和'###'之间的数据时,它为我提供了整个文本文件数据。

Your error is in this line: 您的错误在以下行中:

ui->textBrowser->setText(in.readAll());

It should be: 它应该是:

ui->textBrowser->setText(restOfLine);

Search first for profile index and then for the three #: 首先搜索配置文件索引,然后搜索三个#:

QString srch(contentt + " " + "Profile");
int pos = content.indexOf(srch);
QString srch2("###");
int pos2 = content.indexOf(srch2);
if ( pos1 >= 0 && pos2 >= 0)
    QString restOfLine = content.mid(pos1, pos2-pos1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM