0

This question is based on a previous question that is closed because it asks for a recommendation of a tool.

In Visual Studio 2022, using the Find in Files dialog (CTRL + SHIFT + F) how can I find matches for the following. First I will list the input samples then the expected matches. In the following text, a, b and c are single-word tokens in ASCII encoding.

this->a->b->c;
this->a.b.c;
this->a.b->c;
this->a->b.c;
this->a;

Matches.

a->b->c
a.b.c
a.b->c
a->b.c
NO MATCH

In other words I want to find violations of Law of Demeter. The this and ; token should NOT be a part of the match. If an instance of a class accesses its direct field it shouldn't access any fields of that field.

What have I tried?

\((\b(?!this\b)[\s\S]*?)\)
([\s\S]*?)(this)
this(.|->)(.*(.|->).*(.|->).*)

The regex dialect is the one that C# uses because that's what Visual Studio uses.

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33

1 Answers1

1

To matches described in question you could use this:

(?<=this->)\w+(?:->|\.)\w+(?:->|\.)\w+(?=;)

Edit: corrected regex to match something like this this->a->b()->c(x, y);:

(?<=this->)[\w(), ]+(?:->|\.)[\w(), ]+(?:->|\.)[\w(), ]+(?=;)
  • (?<=this->) - searches for this-> before your match,
  • [\w(), ]+(?:->|\.)[\w(), ]+(?:->|\.)[\w(), ]+ - described pattern to match,
  • (?=;) - checks, that immediately after pattern there is a semicolon.

Demo at regex101

markalex
  • 8,623
  • 2
  • 7
  • 32
  • I tried it in VS2022 and it didn't match `this->a->b()->c(x, y);`. However, this should match because it's similar to the rule `this->a->b->c;` where `b = b()` and `c = c(x, y)`. – sanitizedUser Mar 30 '23 at 15:00
  • @sanitizedUser, `\w` matches only word symbols: letters, numbers and `_`. For regex to match other symbols you need to expand expression. I edited answer to reflex your new example, and added link to regex101, where you can test matches. – markalex Mar 30 '23 at 15:07
  • Good edit. There are of course some false positives because the closure parentheses isn't checked but that's OK. – sanitizedUser Mar 30 '23 at 15:31