1

私のコードは:

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

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

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

qDebug()<<lst;

以下に示すように、キャプチャされたカウントが1で、qstringリストのデバッグ出力が表示されます

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

なんで?

4

1 に答える 1

2

リストの最初の要素は、QRegExp::capturedTexts()一致した文字列全体です。

ドキュメントは次のように述べています。

QStringList QRegExp::capturedTexts() const

キャプチャされたテキスト文字列のリストを返します。

リストの最初の文字列は、一致した文字列全体です。後続の各リスト要素には、正規表現の (キャプチャ) 部分式に一致する文字列が含まれます。

もう一つの例:

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

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

出力は次のようになります。

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

すべての一致を取得したい場合は、これを使用できます。

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;

出力:

all matches: ("Sum(2+3)", "Sum(5+3)") 
于 2016-10-12T07:05:29.237 に答える