summaryrefslogtreecommitdiff
path: root/noncore/applets/keyhelper/keyhelperapplet/misc/StringParser.cpp
blob: 72c15f127db2f36982c3936471d113e3aa605712 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "StringParser.h"

#include <qregexp.h>

QStringList StringParser::split(const QChar& sep, const QString& str,
	bool allowEmptyEntries)
{
	QString line = str + sep;
	QString quote;
	QRegExp rxend;
	QRegExp rxdbl;
	int pos=0, len, idx=0;
	QStringList list;
	while(idx < (int)line.length()-1){
		if(!quote.isEmpty()){
			QString s;
			while((pos = rxend.match(line, idx, &len)) != -1){
				s += line.mid(idx, len+pos-idx-1);
				idx = pos+len-1;
				if(len % 2 == 0){
					s.replace(rxdbl, quote);
					list.append(s.left(s.length()-1));
					idx++;
					break;
				}
			}
			quote = "";
		} else if(line[idx] == '\"'){
			rxend.setPattern(QString("\"+") + sep);
			rxdbl.setPattern("\"\"");
			quote = "\"";
			idx++;
		} else if(line[idx] == '\''){
			rxend.setPattern(QString("\'+") + sep);
			rxdbl.setPattern("\'\'");
			quote = "\'";
			idx++;
		} else if(!allowEmptyEntries && line[idx] == sep){
			idx++;
		} else {
			pos = line.find(sep, idx);
			if(pos != -1){
				const QString& s = line.mid(idx, pos-idx);
				list.append(s);
				idx = pos+1;
			}
		}
		if(pos == -1) break;
	}
	return list;
}

QString StringParser::join(const QChar& sep, const QStringList& list)
{
	QString str;
	QString s;
	QStringList tmp;
	QRegExp quote("\"");
	for(QStringList::ConstIterator it=list.begin();
			it!=list.end(); ++it){
		s = *it;
		if(s.find(sep) != -1
			|| s[0] == '\"'
			|| s[0] == '\''){
			s.replace(quote, "\"\"");
			tmp.append("\"" + s + "\"");
		} else {
			tmp.append(s);
		}
	}
	return tmp.join(sep);
}