PDA

View Full Version : Problem regarding regular expression



aaditya190
12th December 2013, 07:42
I am using some regular expressions in my application. I am making changes to the application mentioned below-:


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

Making changes to the highlighter.cpp file of the application, I have done something like this :-



QTextCharFormat plus,quotationformat;

quotationFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat; // for double quotes
highlightingRules.append(rule);


plus.setForeground(Qt::red);
rule.pattern = QRegExp("\\+");
rule.format = plus;
highlightingRules.append(rule);





The problem I am facing is that if '+' is written inside double quotes , the quotation format rules does not apply on it. Something like this-:
If I write + outside quotes, it is displayed in red like-:


Adding 1 + 2 makes 3.


But If I write it inside quotes like-:


"Adding 1 + 2 makes 3...." ..

I want that + should also appear in blue when i type it inside quotes. Can anyone help me what mistake I am making??

thomas@itest
12th December 2013, 18:28
Hi,

What do you think about adding a precedence tag to the HighlightingRule structure and then use it in void Highlighter::highlightBlock(const QString &text) to determine whether an highlighting rule should be applied or not ?

ChrisW67
12th December 2013, 21:29
Can anyone help me what mistake I am making??
The problem has nothing to do with the title of the thread.

The highlightBlock() function does the heavy lifting by matching all patterns in the order provided and applying the format specified for each match. The way the example is coded it applies the quoted pattern first, then the plus pattern. It doesn't apply just the first pattern matched, or the longest pattern matched, or the "most sensible" pattern matched unless you code it to do so. Open your debugger and single step through that function to see what I mean.

You might get away with applying the rules in opposite order but I expect you have other rules that cannot be "fixed" in the same way. Implementing more complex rules will require more complex code on your part. Thomas@itest had some suggestions but there is a multitude of ways you might want or need to approach your particular problem. You cannot cut and paste your way to a fully fledged syntax highlighting code editor.