Question

From MSDN, seen from the explanation of "CString::Format",

The call will fail if the string object itself is offered as a parameter to Format. Following is an example:

CString str = "Some Data";
str.Format("%s%d", str, 123);   // Attention: str is also used in the parameter list.

Now I want to check whether there are codes in my project went against this rule.

I think regular expression can help me achieve this goal. (I mean the regular expression that is usually built in Editor's search/find file function, not the regular expression used in C#/C++/Java/Python etc)

In short, the expression might look like this:

XXX.Format\(.*XXX.*\)

where the XXX can vary to be a valid variable name. E.g. "str", "sql_string", "_mystr"

Note: I can download any editor like Notepad++, sublime text; I have visual studio. So it is quite ok if you can solve this issue on any editor.

Was it helpful?

Solution

A regular expression like below should do the job (with \1 to reference the first capture group - your variable):

^\s*(.+?)\.Format\(.*\1.*\)

There are a few assumptions and things to note though:

  • I assumed that the variable is the first thing in the line, proceeded by whitespace only.

  • The variable is only checked to appear in brackets after .Format (as you put it in your question). The same variable may appear in the first parameter, the regex currently doesn't check that.

  • You may add additional whitespace to the regex if neeeded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top