PDA

View Full Version : Complex Numbers



Max Yaffe
23rd May 2007, 21:35
Anyone have a good QtRegEx expression for parsing a string into a complex number?
I'm looking for formats including:

A+Bi
A
Bi
i

where A and B are floating point numbers including embedded signs and exponents, i is either "i" or "j". + is either "+" or "-". And spaces can be sprinkled between the patterns.

I've tried "^\\s*(\\S*)\\s*([+-]{0,1})\\s*(\\S*)\\s*([iIjJ])\\s$" but that fails, I think because all the patterns are optional.

I can also match several special cases in sequence but that seems inelegant.

Thanks,
Max

wysota
23rd May 2007, 21:48
First of all you can strip all spaces, so that it is easier to parse the string.

Then try something like this:
((\\d+)|(\\d*(i|j)))?((+|-)((\\d+)|(\\d*(i|j))))+

Seems complicated but should match even a sequence of complex numbers. If you want to match at most one Re and at most one Im component, you can simplify it a bit, but I can't tell you how because my head aches :) Maybe someone else will continue from here...

Max Yaffe
24th May 2007, 17:40
Thanks for your help. I came up with something similar yesterday after I posted the note here:

static QRegExp rx1("^\\s*([+-]?)\\s*(\\d+(?:\\.\\d+)?)([eE][+-]?\\d+)?([iIjJ])?\\s*"); // matches floating point number w/ possible imag. qualifier
if (rx1.indexIn(str) == -1) return false;
QString sFull = rx1.cap(0);
QString sSign = rx1.cap(1);
QString sMant = rx1.cap(2);
QString sExp = rx1.cap(3);
QString sImag = rx1.cap(4);

QString sNew = sSign+sMant+sExp;

bool ok;
double x = sNew.toDouble(&ok);

So basically I find the separate sign, mantissa, exponent and imaginary portions of a single term, skipping whitespace. Then paste the first 3 back together and let .toDouble decide weather it qualifies as a valid double. Then I call this again on the last section.

Thanks again for your help