简体   繁体   中英

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,

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 ###. and If profile name is PQR then I want the text between PQR Profile to ###. The no of a profile maybe increase.

I have tried like this, here detail_data.txt file contains only my profile name.

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 '###'.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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