Главная > C++, программирование > Parsing .csv with Qt regexp

Parsing .csv with Qt regexp

This code gets all fields in .csv line, works for most cases


QStringList parseLine(const QString &line)
{
// Match against comma, followed by optional \", followed by target, followed by optional \" then comma or end of line
QRegExp rx("(?:^|,)(?:\\s*)\"(.*)\"(?:\\s*)(?:,|$)|(?:^|,)(?:\\s*)([^\"]*)(?:\\s*)(?:,|$)",Qt::CaseSensitive,QRegExp::RegExp2);
rx.setMinimal(true);
QStringList list;
int pos = 0;

while ((pos = rx.indexIn(line, pos)) != -1) {
list << (rx.cap(1).isEmpty() ? rx.cap(2) : rx.cap(1));
pos += rx.matchedLength()-1;
}

return list;
}

Добавить комментарий

Fill in your details below or click an icon to log in:

Логотип WordPress.com

You are commenting using your WordPress.com account. Log Out / Изменить )

Фотография Twitter

You are commenting using your Twitter account. Log Out / Изменить )

Фотография Facebook

You are commenting using your Facebook account. Log Out / Изменить )

Connecting to %s

Follow

Get every new post delivered to your Inbox.