1

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;

  • Are you trying to support comments that go across lines? This is not likely to be an easy problem, though it might be manageable depending on the problem constraints. – Louis Wasserman Mar 16 '22 at 23:36
  • @LouisWasserman I'm talking about the operators inside the comment, because they are in the comments, they should not be included in the Total number of operators or operands. – user15465584 Mar 17 '22 at 00:47
  • 1
    FYI: http://JavaParser.org/ or [ANTLR](https://en.wikipedia.org/wiki/ANTLR) – Basil Bourque Mar 17 '22 at 00:52
  • The JFlex manual starts with [an example](https://jflex.de/manual.html#ExampleUserCode) which could easily be modified to add the additional operators you need to count. – rici Mar 17 '22 at 01:52
  • Wrong tool for the job entirely. Don't try this. You will need a Java-compliant lexer and grammar, such as come with JavaCC. – user207421 Mar 17 '22 at 02:38

1 Answers1

-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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • I also think so ,thanks.I did not get why this answer get downvote is there something wrong in it – user15465584 Mar 17 '22 at 11:28
  • Probably because if you really want something that'll guarantee it works for every Java file, you can't use regexes at all, you have to use a full Java parser. I _do_ think this will be adequate for beginner use cases, though. – Louis Wasserman Mar 17 '22 at 17:29
  • (I had the same reaction at first, but for sanely built files this should work perfectly fine.) – Louis Wasserman Mar 17 '22 at 19:02