Eclipse: how to search a string, but not in comments

How to search for "*" (multiplication operator) in the source code?

Not an asterisc character (in comments, etc.). Just an operator *!

/** foo method */ // <- this should not be in search results public int foo(int i, int j) { /* compute the values */ // <- this should not be in search results return i * j; // <- this should be in search results } 
+4
source share
3 answers

It's impossible. Searching for an Eclipse file is unaware of comments, so you cannot easily exclude results in comments. (Semantic) Java search does not allow you to search for operators, only types, methods, etc. (The weakness of the search dialog box, allowing you to search for texts that are not or legal identifiers, is similar to text search, but it is not).

Thus, you can help yourself in finding files with regular expressions, which may work in most of your cases, but will not be 100% correct and depending on the style of comments and string literals in your source may not work.

Write a regular expression that looks for everything * except for "//", "/" or ("" at the beginning of a line or only after spaces). Especially the latter case can be problematic depending on where you violate lengthy mathematical terms. If you leave the operator as the last character on the previous line, this is not a problem if it is the first character on a new line. In this case, depending on the urgency of the search, you might consider reformatting your sources for the search. Reformatting everything in Eclipse is pretty simple.

0
source

This regex performed the trick:

 ^(?!\s*(//|\*|/\*)).*\* 
+1
source

You can search through Eclipse using regex search, and I decided to use regex. Here you can see an example here . The example has a bunch of different comment blocks that I used to test the regular expression.

(?mx)(?<![\/\*+\n])\*+(?![\n\*+\/])

It includes a combination of three parts:

  • A negative look at / followed by 1 or more * indicates the beginning of the comment.
  • The actual match we are looking for \*+ , or "one or more" *
  • A negative look at the end of the comment block * in any quantity followed by / .

mx at the beginning tells the regex to look at multiple lines. Therefore, when it fires, it searches for the middle template \*+ , which is NOT preceded by any initial comment, and does NOT end with any final comment (regardless of how much * used).

This can be changed to find any template that is not in the Java comment, no matter how big or crazy the "art" of the comment. Using (?mx)(?<![\/\*+\n])PATTERN_GOES_HERE(?![\n\*+\/]) and replacing PATTERN_GOES_HERE with a template so that it is not included in the comment. This will allow you to insert any crazy template you need, where an important part of it is not contained inside the comment, it is processed with a negative rear / front view.

0
source

All Articles