00001 #include "StringParser.h"
00002
00003 #include <qregexp.h>
00004
00005 QStringList StringParser::split(const QChar& sep, const QString& str,
00006 bool allowEmptyEntries)
00007 {
00008 QString line = str + sep;
00009 QString quote;
00010 QRegExp rxend;
00011 QRegExp rxdbl;
00012 int pos=0, len, idx=0;
00013 QStringList list;
00014 while(idx < (int)line.length()-1){
00015 if(!quote.isEmpty()){
00016 QString s;
00017 while((pos = rxend.match(line, idx, &len)) != -1){
00018 s += line.mid(idx, len+pos-idx-1);
00019 idx = pos+len-1;
00020 if(len % 2 == 0){
00021 s.replace(rxdbl, quote);
00022 list.append(s.left(s.length()-1));
00023 idx++;
00024 break;
00025 }
00026 }
00027 quote = "";
00028 } else if(line[idx] == '\"'){
00029 rxend.setPattern(QString("\"+") + sep);
00030 rxdbl.setPattern("\"\"");
00031 quote = "\"";
00032 idx++;
00033 } else if(line[idx] == '\''){
00034 rxend.setPattern(QString("\'+") + sep);
00035 rxdbl.setPattern("\'\'");
00036 quote = "\'";
00037 idx++;
00038 } else if(!allowEmptyEntries && line[idx] == sep){
00039 idx++;
00040 } else {
00041 pos = line.find(sep, idx);
00042 if(pos != -1){
00043 const QString& s = line.mid(idx, pos-idx);
00044 list.append(s);
00045 idx = pos+1;
00046 }
00047 }
00048 if(pos == -1) break;
00049 }
00050 return list;
00051 }
00052
00053 QString StringParser::join(const QChar& sep, const QStringList& list)
00054 {
00055 QString str;
00056 QString s;
00057 QStringList tmp;
00058 QRegExp quote("\"");
00059 for(QStringList::ConstIterator it=list.begin();
00060 it!=list.end(); ++it){
00061 s = *it;
00062 if(s.find(sep) != -1
00063 || s[0] == '\"'
00064 || s[0] == '\''){
00065 s.replace(quote, "\"\"");
00066 tmp.append("\"" + s + "\"");
00067 } else {
00068 tmp.append(s);
00069 }
00070 }
00071 return tmp.join(sep);
00072 }