'How To Count All Operands And Operators in a Java File

I have a java file and i want to count the number of binary,unary,logical operators,and operands in it.I just know i need to use regex for it and i know the basic of it.The task might be simple but what i can't figure out is that there are comment lines, so I dont know how to do this exactly. For example suppose i read a .java file into a EXAMPLE_TEST string;(first line1 has been read and processed in the code, after line2 has been read and processed.To keep it simple, I'm not writing the file reading part.)For line 1 output would be 2 ,but for line 2 output will be a number that unexpected because it is in the comment section.Can you show me a way to do this I'm just a beginner in java and stuck.

 int counter=0;
 Pattern pattern = Pattern.compile("[+-*%]");  
 Matcher matcher = pattern.matcher(EXAMPLE_TEST);
      
        while (matcher.find()) {
            
            System.out.println(matcher.group());/*print what have found in string between (+-*%)   */
           counter++;
        }
       System.out.println(counter);//print the number of operators found

content of .java file example: /* line1 is between comment lines */

/* a=a+4 ; b++; */

/* line2 is not between comment lines */

b=b+8 ; c=d%10;



Solution 1:[1]

Your best bet is probably going to be to process the entire file with regexes to remove comments entirely -- to get an entire new version of the file -- and then to scan for operators.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Wasserman