0

Taken from Qt Syntax Highlighter Example:

//single line comment rule
singleLineCommentFormat.setForeground(Qt::darkGray);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
//string rule
quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("\".*\"");
rule.pattern.setMinimal(true);
rule.format = quotationFormat;
highlightingRules.append(rule);

The Problem is when you have something like this:

"inside is darkGreen//"outside is darkGray

As you can see, the result is: inside the quotations will be gray including the double / . But the characters outside "" becomes darkGray which is supposed to be in default font color(normally, black). How do i adjust the RegExp for single line comment inorder for it to know that a green "//" is exempted from the darkGray highlighting rule?

I tried to add this for the singe line comment rule:

rule.pattern.setMinimal(true);

Still won't work. I Also tried:

rule.pattern = QRegExp("//[^\n]*\"*");
Alex Pappas
  • 2,377
  • 3
  • 24
  • 48

1 Answers1

0
/(\"(?:(?!\/\/).)+?\")/

Using the magic of non-capturing groups and negative look aheads, I have engineered the following:

quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("\"(?:(?!\\/\\/).)+\"");//QRegExp("\".*\"");

rule.pattern.setMinimal(true);
rule.format = quotationFormat;
highlightingRules.append(rule);

Magic applied, and you get the behavior you are looking for.

References:

https://stackoverflow.com/a/977294/999943

http://regexr.com/3an21

and also tested in this example:

http://doc.qt.io/qt-5/qtwidgets-richtext-syntaxhighlighter-example.html

Hope that helps.

Community
  • 1
  • 1
phyatt
  • 18,472
  • 5
  • 61
  • 80
  • Wouldn't this be enough?: `(\"[^/"]+\")` – murison Mar 27 '15 at 18:52
  • But then you can't put a single forward slash inside double quotes. Also, I don't think non-capturing groups is a requirement, but I didn't study to see if capture groups were leveraged elsewhere in the code. – phyatt Mar 27 '15 at 18:52
  • This is the output: "all are black before //"the rest are gray – Alex Pappas Mar 28 '15 at 02:17