QRegExp and double-quoted text for QSyntaxHighlighter

喜你入骨 提交于 2020-01-14 06:05:44

问题


What would the QRegExp pattern be for capturing quoted text for QSyntaxHighlighter?

Test Pattern

"one" or "two" or "three"

So far I have tried:

QRegExp rx("\\0042.*\\0042");
QRegExp rx("(\\0042).*?\\1");

The last pattern succeeds on regexpal.com but not with the QRegExp class.


回答1:


EDIT: If you check out the Syntax Highlighter Example, already has this one in there.

http://qt-project.org/doc/qt-4.8/richtext-syntaxhighlighter-highlighter-cpp.html

 quotationFormat.setForeground(Qt::darkGreen);
 rule.pattern = QRegExp("\".*\"");
 rule.format = quotationFormat;
 highlightingRules.append(rule);

Just copy most of the code from Qt's highlighter example and you should be set.

Greedy v. Lazy Match in QRegEx

In the description of Qt's variation on RegEx, it says:

Note: Quantifiers are normally "greedy". They always match as much text as they can. For example, 0+ matches the first zero it finds and all the consecutive zeros after the first zero. Applied to '20005', it matches'20005'. Quantifiers can be made non-greedy, see setMinimal().

If you use setMinimal(true) to get the effect of lazy matching instead of greedy matching, you can pull it off. Other regex evaluators use something like *? or +? to perform a lazy match. Sometimes I use gskinner's regex engine to test my expressions.

Below is the code you are looking for. It is based heavily on the example given here.

#include <QCoreApplication>
#include <QRegExp>
#include <QDebug>
#include <QStringList>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString str = "\"one\" or \"two\" or \"three\"";

    QRegExp rx("\".*\"");
    rx.setMinimal(true);
     int count = 0;
     int pos = 0;
     while ((pos = rx.indexIn(str, pos)) != -1) {
         ++count;
         pos += rx.matchedLength();
         qDebug() << rx.cap();
     }

    return a.exec();
}

Hope that helps.



来源:https://stackoverflow.com/questions/16073401/qregexp-and-double-quoted-text-for-qsyntaxhighlighter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!