假設目前有一個檔案內容如下
Config.txt
#
# This is mark
#
# Show Log or not
ShowLog = YES
# Print the User Name
PrintMyName = NO
# Show my age or not
ShowMyAge = YES # Comment for this item
程式碼如下:
main.cpp
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QRegExp>
#include <QStringList>
int main (int argc, char *argv[])
{
// QCoreApplication a (argc, argv);
QFile File ("Config.txt");
QString TempString;
QStringList TempStringList;
//
// Try to open file
//
if (!File.open (QIODevice::ReadOnly)) {
qDebug () << "Can Not open File!!";
return -1;
}
QTextStream out (&File);
//
// Insert all the string into TempStringList except the string start with '#' char and null line
//
QRegExp MarkReg ("^[^#].*$");
while (!out.atEnd ()) {
TempString = out.readLine ();
if (TempString.isEmpty ()) {
//
// If the line is null line, judge the next line
//
continue;
}
if (MarkReg.indexIn (TempString) != -1) {
// qDebug () << TempString;
TempStringList << TempString;
}
}
//
// Print the string in the TempStringList
//
for (int i = 0; i < TempStringList.size (); i++) {
// qDebug () << TempStringList.at (i);
}
//
// Print the string with YES flag in the end of the line
//
QRegExp YesReg ("^(\\w+)\\s*=\\s*(YES)\\s*$");
for (int i = 0;i < TempStringList.size(); i++) {
if (YesReg.indexIn (TempStringList.at (i)) != -1) {
// qDebug () << TempStringList.at (i);
// qDebug () << YesReg.cap (1);
}
}
//
// Print the string with NO flag in the end of the line
//
QRegExp NoReg ("^(\\w+)\\s*=\\s*(NO)\\s*$");
for (int i = 0; i < TempStringList.size (); i++) {
if (NoReg.indexIn (TempStringList.at (i)) != -1) {
// qDebug () << TempStringList.at (i);
// qDebug () << NoReg.cap (1);
}
}
//
// Print the string with YES or NO flag in the end of the line
//
QRegExp YesNoReg ("^(\\w+)\\s*=\\s*(YES|NO)(\\s*|\\s*#.*)$");
for (int i = 0; i < TempStringList.size (); i++) {
if (YesNoReg.indexIn(TempStringList.at (i)) != -1) {
// qDebug () << TempStringList.at (i);
qDebug () << YesNoReg.cap (1) << "is" << YesNoReg.cap (2);
}
}
// return a.exec ();
return 0;
}
參考資料:
QStringList Class Reference
QTextStream Class Reference
QRegExp Class Reference
沒有留言:
張貼留言