Originally Posted by
d_stranz
You could try making two passes. In the first pass, do not use "+" or "-" in your reg exp. Take the string list result from pass 1 and examine each entry to see if it matches a reg exp for a number (you can search online for suitable regular expressions). If it matches, keep it. If not, then submit the substring to a second pass that splits on your original reg exp in Line 10.
It is hard to write a single regular expression that will match arbitrary string expressions in a single pass. This is why the lex / yacc and flex / bison tools exist.
I did use two passes, but still fail. I use the following string for test
"a-aa+bb+4.4e-05-1.2e+2"
It should split into "a", "aa", "bb", "4.4e-05", "1.2e+2", but it doesn't. Please help.
Here is my code
#include <QStringList>
#include <QRegExp>
#include <QDebug>
static QStringList getFormulaVarList
( const QString
& formula
) {
foreach( const QString& str, formula.split( opRx, behavior ) ) {
bool ok;
str.toDouble( &ok );
if ( !ok ) {
strList << str.split( plusMinus, behavior );
}
}
strList.removeDuplicates();
foreach( const QString& str, strList ) {
bool ok;
str.toDouble( &ok );
if ( !ok && !str.startsWith( "math.", Qt::CaseInsensitive ) ) {
result << str;
}
}
result.removeDuplicates();
return result;
} // getFormulaVarList
int main( int argc, char** argv )
{
//QString formula( "Stage1 <= 4.4e-05 || Stage == 1.2 && Comp >= 1.4e+03 || A+e-C > D" );
//QString formula( "a * aa+4.4e-05 + math.log( b )" );
//QString formula( "a * aa + 4.4e-05 + math.log( b )" );
qDebug() << "formula =" << formula;
qDebug() << "items =" << getFormulaVarList( formula );
}
#include <QStringList>
#include <QRegExp>
#include <QDebug>
static QStringList getFormulaVarList( const QString& formula )
{
QString::SplitBehavior behavior = QString::SkipEmptyParts;
QRegExp opRx( "[*/()<>&=| ]" );
QRegExp plusMinus( "[+\\-]" );
QStringList strList;
foreach( const QString& str, formula.split( opRx, behavior ) ) {
bool ok;
str.toDouble( &ok );
if ( !ok ) {
strList << str.split( plusMinus, behavior );
}
}
strList.removeDuplicates();
QStringList result;
foreach( const QString& str, strList ) {
bool ok;
str.toDouble( &ok );
if ( !ok && !str.startsWith( "math.", Qt::CaseInsensitive ) ) {
result << str;
}
}
result.removeDuplicates();
return result;
} // getFormulaVarList
int main( int argc, char** argv )
{
//QString formula( "Stage1 <= 4.4e-05 || Stage == 1.2 && Comp >= 1.4e+03 || A+e-C > D" );
//QString formula( "a * aa+4.4e-05 + math.log( b )" );
//QString formula( "a * aa + 4.4e-05 + math.log( b )" );
QString formula( argv[ 1 ] );
qDebug() << "formula =" << formula;
qDebug() << "items =" << getFormulaVarList( formula );
}
To copy to clipboard, switch view to plain text mode
Bookmarks