对于你的特定实例中,这将工作:
#include <QRegExp>
#include <QString>
#include <iostream>
int main()
{
//Here's your regexp.
QRegExp re("\"[^\"^=]+\"");
//Here's your sample string:
QString test ="<S id=\"1109\" s5=\"1\" nr=\"1183\" n=\"Some text\" test=\" \" x=\"20.53843\" y=\"50.84443\">";
int offset = 0;
while(offset = re.indexIn(test, offset + 1))
{
if(offset == -1)
break;
QString res = re.cap().replace("\"", "");
bool ok;
int iRes;
float fRes;
if(res.toInt(&ok) && ok)
{
iRes = res.toInt();
std::cout << "int: " << iRes << std::endl;
}
else if (res.toFloat(&ok) && ok)
{
fRes = res.toFloat();
std::cout << "float: " << fRes << std::endl;
}
else
std::cout << "string: " << res.toStdString() << std::endl;
}
}
输出将是;
int: 1109
int: 1
int: 1183
string: Some text
string:
float: 20.5384
float: 50.8444
另外,关于不试图使用正则表达式解析XML/HTML的义务性评论:http://stackoverflow.com/a/1732454/183339。你可以使用QXmlStreamReader吗? – 2012-07-13 12:17:07
@DaveMateer我认为这不是使用QXmlStreamReader :)。 – poplawskidaniel 2012-07-13 12:31:06