1

My Code is :

QString strExp="Sum(2+3)-Sum(5+3)";

QRegExp regexp("(Sum\\([^)]*\\))");
regexp.indexIn(strExp);

QStringList lst=regexp.capturedTexts();
qDebug()<<"CapturedCounts:"<<regexp.captureCount();

qDebug()<<lst;

I have getting captured count is 1 and qstring list debug output as shown below

("Sum(2+3)", "Sum(2+3)").

Why?

1 Answers1

2

The first element of the QRegExp::capturedTexts() list is the entire matched string.

The doc says:

QStringList QRegExp::capturedTexts() const

Returns a list of the captured text strings.

The first string in the list is the entire matched string. Each subsequent list element contains a string that matched a (capturing) subexpression of the regexp.

Another example:

QString s = "abcd123";
QRegExp re("(ab).*(12)");

qDebug() << "indexIn:" << re.indexIn(s);
qDebug() << "captureCount:" << re.captureCount();
qDebug() << "capturedTexts:" << re.capturedTexts();

Output will be:

indexIn: 0 
captureCount: 2 
capturedTexts: ("abcd12", "ab", "12") 

If you want to get all matches, you can use this:

QString strExp="Sum(2+3)-Sum(5+3)";

QRegExp regexp("(Sum\\([^)]*\\))");
regexp.indexIn(strExp);

QStringList list;
int pos = 0;

while ((pos = regexp.indexIn(strExp, pos)) != -1) {
    list << regexp.cap(1);
    pos += regexp.matchedLength();
}

qDebug() << "all matches:" << list;

Output:

all matches: ("Sum(2+3)", "Sum(5+3)") 
hank
  • 9,553
  • 3
  • 35
  • 50