Could someone please tell me whether the Regex expression is correct?
Hi,
I am trying to find the cyclomatic complexity of a method using regex. The code that I have written is given below:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
class cyclomaticCalculator
{
// uses the java i/o.
static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
protected String txtFileName;
protected int count = 1; // start count at one then no need to add 1 to count!
private static BufferedReader reader;
// Uses the java.io.*;
public void Cyclomatic() throws IOException
{
try {
// open the file
System.out.println("------------------------------" );
System.out.println("CYCLOMATIC COMPLEXITY PROGRAM " );
System.out.println("------------------------------" );
//System.out.println("Enter file name to be read: " );
// Create object to read textfile from keyboard
txtFileName = "C:\\Documents and Settings\\227951\\workspace\\Decompiler\\test\\And Or.java";
System.out.println("\n \n");
// the buffered reader object
reader = new BufferedReader(new FileReader(txtFileName));
// Pattern for keywords and the start of comments
Pattern p1 = Pattern.compile("(/\\*)|(//)|(\".*?\")|(if|for|while|case|switch)");
Matcher m1 = p1.matcher("");
// Pattern for the end of multiline comments
Pattern p2 = Pattern.compile("\\*/");
Matcher m2 = p2.matcher("");
//Pattern for logical operators
// Pattern for logical operators
/* Pattern p3 = Pattern.compile("(\\&&)|(\\||)");
Matcher m3 = p2.matcher("");
*/
boolean inComment = false;
int lineNum = 0;
String line = null;
while ((line = reader.readLine()) != null)
{
lineNum++;
int startAt = 0;
if (inComment)
{
// In multiline comment; see if it ends in this line
if (m2.reset(line).find())
{
inComment = false;
startAt = m2.end();
}
else
{
continue;
}
}
m1.reset(line);
while (m1.find(startAt))
{
if (m1.start(1) != -1)
{
// Start of multiline comment
if (m2.reset(line).find(m1.end()))
{
// If it ends in this line, we'll keep looking for keywords
startAt = m2.end();
}
else
{
// ...otherwise, just set the flag
inComment = true;
break;
}
}
else if (m1.start(2) != -1)
{
// End-of-line comment
break;
}
else if (m1.start(3) != -1)
{
// String literal
startAt = m1.end();
}
else
{
// It's a keyword
count++;
break;
}
}
}
System.out.println("Cyclomatic Complexity : "+count);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main (String[]args)
{
// Create object Complex
cyclomaticCalculator Complex = new cyclomaticCalculator();
try {
Complex.Cyclomatic();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
how do I check for logical && and logical || operator in the above pattern p1? Please help.