In a project I'm working on, I need to make a QStringList
out of all QRegExp
captures except for 2 of them: the 1st one and one of the other ones, depending on some other parameters.
The straightforward approach would be to use QRegExp::capturedTexts()
and then remove from the returned list the two unneeded items. This however implies that two QStrings
and related QList
's nodes need to be allocated just to be trown away without any real use, which seems wasteful.
I then thought I would just build a QStringList
myself one captured text at time, via QRegExp::cap()
. But QRegExp::cap()
is itself implemented in terms of QRegExp::capturedTexts()
, which would make my code look funny, at the very least.
So I looked at the API and found the pretty convenient QRegExp::pos()
method, which, the documentation states, «Returns the position of the nth captured text in the searched string.»
Pretty neat, I thought, I could then use QString::mid()
and build the QStringList
myself. This is what the actual implementation of QRegExp::capturedTexts()
does, after all.
Except I wouldn't know how to retrieve the nth captured text length, which I need to extract the captured text by means of QString::mid()
. Indeed, the position and the length of any of the captured texts are stored one beside the other, as can be seen in the QRegExp::pos()
implementation, but there's no accessor for the length info, unless I'm terribly mistaken, a case for which I apologize in advance. :)
So, here's my question: if I'm correct and there's no way to retrieve any given captured text's length, what use case does QRegExp::pos()
have? I can't imagine any situation in which I'd want to know just where the captured text begins, without being able to retrieve it.
__
PS. Qt5 QRegularExpressionMatch
class provides the methods capturedStart()
and capturedEnd()
that fill this void, but I'm stuck with Qt4.8.6.
It's an API bug. That's all. I wish there was some magic trick to it - there isn't, as far as I know. I wouldn't worry too much about allocating the capturedTexts
return value unless this is a parser that is invoked on lots and lots of text. Use what you've got - probably any time you spend on tweaking this is time wasted at this point unless you're pushing millions of lines of text through this thing.