How to search in a text and take the first match?
-
So for example we have QString leon="1234,1235,1234,123456"
I want for example to qdebug() the number that starts from 1 and ends with 4.. But only the first match..
so the qdebug() must show 1234, and not 12341234123456QRegExp does the job but shows 12341234123456 while i want only the first match..
-
This is pretty standard and straight forward case. You have several options to do it. For example you can "split":http://doc.qt.nokia.com/4.7-snapshot/qstring.html#split the QString into QStringList and to loop through QStringList items until you find an item that matches your criteria (the number that starts from 1 and ends with 4).
-
A QRegExp should work, too.
-
[quote author="Tobias Hunger" date="1343552204"]A QRegExp should work, too.[/quote]
basically it won't... see
@QString lool="1/n3/n5/n6/n7/3/n5/n9";
QRegExp reg2("3.*5");
if(reg2.indexIn(lool) != -1){
QStringList list;
QString strq;
list = reg2.capturedTexts();
foreach(strq,list)
qDebug(strq.toLocal8Bit());
}@
it will show
3/n5/n6/n7/3/n5
while i want from it to show
3/n5 -
QRegExp will work...You have to turn off the ‘greedy’ mode for this, as I posted "here":http://qt-project.org/forums/viewthread/19102/#93187 :
[quote author="raaghuu" date="1343563395"]You have to turn off the 'greedy' mode for this... see "here":http://qt-project.org/doc/qt-4.8/qregexp.html#setMinimal[/quote] -
Leon: You are doing it wrong then:-)
QRegExp reg("^(\d*),") will match every number from the start of the line to the first comma. Note that you are interested in the reg.capturedTexts().at(1).
The regexp will be a bit more complex if you want to allow for spaces in front/after the number:
QRegExp reg2("^\s*(\d*)\s*,) will do that (also in capturedTexts().at(1)). -
If you are trying to search for a number that starts with 1 and ends with 4 in a string you could first search for the number 1. When it finds the number 1 (you save the position so you can come back later and do more comparisons if you wish to), it searches for the number 4 by comparing each character after the 1 with "4". In the meantime, while you move through the string you have to save the numbers into another string. When the number 4 is found you end the comparison.
I am not familiar with QRegExp but I read the documentation and it should do the job.