1

I have a QPlainTextEdit and want to select specific text in it using QRegExp

here is example of a text block:

Block1 = Foo1 {
     bla bla bla;
     bla bla bla;
}

I need to select starting from = till } given the sub-string Foo1

Here is my code:

QString name = "Foo1";
QString pattern = "[\\=][\\s]" + name + "[\\s][\\{](^\\})*[\\}]";
//pattern = "[\=][\s]Foo1[\s][\{](^\})*[\}]"

and these lines for selection:

this->moveCursor(QTextCursor::Start);
this->document()->find(QRegExp(pattern));

and strangely, this select only Foo1 not

= Foo1 {
     bla bla bla;
     bla bla bla;
}
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Mahmoud Hassan
  • 598
  • 1
  • 3
  • 15

1 Answers1

2

The problem

Here is your final regex for Foo1:

[\=][\s]Foo1[\s][\{](^\})*[\}]


And here is what QRegExp understands:

Regular expression visualization

The solution

So here is what you should tell it:

=\s*Foo1\s*{[^}]+}

and what it'll understand:

Regular expression visualization

There is more...

  • In the solution I admit that no } can appear in the code. Otherwise, regex are not well suited for handling this case. If this happens in your context, you should rely on parser instead of regexes.
  • Use Debuggex to visualize your regex.
Stephan
  • 41,764
  • 65
  • 238
  • 329
  • well, I tried part of your pattern `=\s*Foo1\s*{` and it doesn't make any match (as it should), while this pattern `\=\s*Foo1\s*\{` matches with `= Foo1 {` so the "\" escape character is needed I guess, however this pattern `\=\s*Foo1\s*\{[^\}]+\}` still doesn't make any match. While in debuggex.com it makes the correct match !! – Mahmoud Hassan Nov 13 '13 at 12:19
  • Also I noticed there are several Pattern Syntax for QRegExp but not sure which one I should use http://qt-project.org/doc/qt-4.8/qregexp.html#PatternSyntax-enum – Mahmoud Hassan Nov 13 '13 at 12:21