我想使用正则表达式在“(引号)之间的字符串(或QString)中找到某些内容。
我简单的字符串:x =“20.51167”,我想要20.51167。
正则表达式可能吗?
开始时,我有点像这样的字符串:<S id="1109" s5="1" nr="1183" n="Some text" test=" " x="20.53843" y="50.84443">
使用如下正则表达式:(nr=\"[0-9]+\")
(y=\"[0-9 .^\"]+\")"
etc
我得到了简单的字符串,例如x =“20.51167”。也许这是错误的方式,我可以一次获得介于引号之间的值?
最佳答案
对于您的特定示例,这将起作用:
#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