Cyclomatic Complexity Using Regex

/ Cyclomatic Complexity Program               /
/          Program does not ignore comments in pattern /
/ Program looks for 1 pattern keywords then moves down a line for next search/
/ java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html     /                                   /
/ Using Java Regular Expression Class               /
import java.util.regex.Matcher;
import java.util.regex.Pattern;     
import java.io.*;
class Cyclomatic
          // 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()
          try {
                    // open the file
                    System.out.println("------------------------------" );
                    System.out.println("CYCLOMATIC COMPLEXITY PROGRAM " );
                    System.out.println("------------------------------\n\n" );
                    System.out.println("Enter file name to be read: " );
                    // Create object to read textfile from keyboard
                    txtFileName = new String(keyboard.readLine());
                    System.out.println("\n \n");
                    // the buffered reader object
                    reader = new BufferedReader(new FileReader(txtFileName));
                    // Create a pattern object and split the key words using pipes |||
                    Pattern pattern = Pattern.compile("if|for|while|case|switch",Pattern.MULTILINE);
                    Matcher m = pattern.matcher(txtFileName);
                    boolean b = m.matches(); // return true if match found !
                    String line = null;
                    while((line = reader.readLine()) !=null)
                         m.reset(line);
                         if(m.find())
                              count = count +1;
                              System.out.println("KeyWord " + " found " + " start of line: " + m.start() + " ends at line: " m.end() " Keyword count = "+ count);
                    reader.close(); // close buffered reader!
                    if(count >10)
                         System.out.println("\n \nThis program according to McCabe has a COMPLEXITY OF: " + count +" \n");
                    else
                         System.out.println("\n \n This program is NOT COMPLEX \n \n");
               catch(IOException e)
                    System.out.println("Error : " + e.getMessage());
     // Run the thing!
     public static void main(String[]args)
          // Create object Complex
          Cyclomatic Complex = new Cyclomatic();
          Complex.Cyclomatic();
Does anyone have ideas as how to improve this program so that it can
ignore keywords inside comments, it finds the first keyword on a line
then jumps down to the next line to search. I know how to implement
this program using the Stream Tockenizer Class using the slashStar
comments, just interested in this alternative that I thought of. It works fine
when givin the following test file. Just want to iorn the few problems out.
Test File:
// SAVE AS A TEXT FILE AND OPEN WITH PROGRAM //
// Cyclomatic Complxity for this file is 17 //
1.     if
2. if
3.     while
4.     for
5.     if
6.     case
7.     case
8.     if
9.     switch
10.     for
11.     if
12.     while
13.     if
14.     if
no
     dont
     count
     this
15.     if
16.     for
Gives Correct CC for this layout.

Please use [code] tags when posting source code.
End-of-line comments are easy to handle, but the multiline varieties complicate the task quite a bit. They can span multiple lines, but they don't have to, and keywords can occur after the end of a multiline comment. Since you're reading the file line-by-line, you need to use a flag to handle comments that actually span multiple lines. For the rest, you've got capturing groups and the find(int) method:      // 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("");
      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
            // It's a keyword
            count++;
            // If you aren't using Java 5, go back to the old way
            System.out.printf("Keyword found in line %2d at position %2d; Keyword count = %2d\n",
                              lineNum, m1.start(), count);
            // We only care about the first one
            break;
      }Here's the test data I used:1. if
2. if
3. while
4. don't count this // switch
5. for
6. if
7. don't count this /* case
8. for */ ...or this
9. case
10. /* yes count this */ case
11. if
12. switch
13. for
14. if
15. while
16. if
17. if
18. no
19. dont
20. count
21. this
22. if
23. for

Similar Messages

  • How to calculate the sum of cyclomatic complexity of all methods?

    I can write a rule to calculate the sum of cyclomatic complexity of all methods in my system?

    Hi Dileep,
    In your query you are not specified whether the SUM of entire internal table SALARY or break up SALARY.
    If you want just the SUM of the entire internal table SALARY.
    Try this code.
    begin of itab occurs 0,
      name(10),
      salary type i,
    end of itab.
    itab-name = 'ABC'. itab-salary = 25000.
    append itab.
    itab-name = 'CDF'. itab-salary = 50000.
    append itab.
    itab-name = 'FGH'. itab-salary = 30000.
    append itab.
    itab-name = 'LMN'. itab-salary = 35000.
    append itab.
    itab-name = 'QPR'. itab-salary = 40000.
    append itab.
    loop at itab.
      at last.                "  Note the control statement used here
        sum.
        write: 'The total salary is',itab-salary.
      endat.
    endloop.
    Regards,
    Smart

  • How To Color a Text string using Regex (java.util.regex)

    Hello,
    How can I color a text string using regex class in 1.4?

    Yes, did you notice it said something about incredibly vague functionality?
    Let me break it down for you
    > How can I color a text string
    Strings do not have color... You can color a component (a label, a button), but you can't color a string
    > using regex class in 1.4?
    Using a regular expression? How would a regular exression color anything? Do you have embedded color codes? Are you searhing a string for some secret word?
    What are you talking about?

  • How to design a program which determines cyclomatic complexity-advice plz!

    Hi there,
    I've been asked to design a program to detect the cyclomatic complexity of a module read in from a text file. The program should then display whether or not the module is far too complex or not.
    The problem I am having is as follows:
    In what way should I test the complexity?
    I could count the number of conditional statements and add 1. Possible problems here may be mis-counting(difference between do-while and while).
    Any advice would be great,
    Thanks in advance
    Chris,

    The difference between while and Do while is irrelevant. They are both while loops and can be counted by just counting the while part, the do can be ignored.
    while (x<y){
    xxxxxxxxxxx
    do{
    xxxxxxxxxxx
    }while(x<y)

  • Parse html (a href) using regex

    Hello,
    i would like to extract all the urls from a website that are included in < a href=" parse string">
    I have already the regex which is
    String regex = "< *a.*href *= *['|\"]";
    May you please advise me which method in Pattern or Matcher classes shall i use in order to take as output
    *only* the url inside the " " marks?
    I have already tried end and start methods which return the indexes, but i don't get the desirable result.
    Thanks, in advance
    P.S.Also, i have already tried to use HtmlParser but i prefer to use regex cause i found a difficulty in it.

    Please continue in your original thread.
    [http://forums.sun.com/thread.jspa?threadID=5363751]

  • How to Use Regex Options in CS2 [JS] - Reg.

    Dear All,
    Hai, I have doubt about the Regex options using in CS2 - Script.
    Problem :
    filename = "FTR0123a.indd";
    k = Regex.match(filename,"(^FTR)(\d+)([A-Z*])\.(indd|indt))
    if k.match = success
    k1 = "."
    k2 = $1 [ Stored in First Value only]
    k3 = $2 [ Stored in Second Value only]
    Here I got the answers from VB.NET using Regex options. But I can't use the Same condition in Javascript.
    Please any one can give the solutions about the problem.
    Thanks & Regards
    T.R.Harihara SudhaN

    The correct format is
    filename = "FTR0123a.indd";
    k = filename.match (/^(FTR)(\d+)([A-Za-z]*)\.(indd|indt)/);
    This gives a five-element array, which you can see when you try this in the ESTK.
    Peter

  • SAP IDM : Using regex for password

    Hi experts,
    I need your help about regex.
    We are trying to use this to be sure that password set in Web inteface by users are correct according to the company policies :
    - The first character cannot be a number
    - The three first characters cannot be the same
    We finally found the following expression to test what we want (reponse is "true" when one of the policies is ok) :
    (.)(1)|(d)
    But IDM never accept any password with that expression.
    So my questions are :
    1) Does IDM need a special regex language or is it the same than PERL language for example?
    2) Does anybody know how to use regex in our policies case?
    Thanks a lot for your response.
    Regards.
    Jérémy.

    Thanks a lot for your answers.
    Actually, i am already doing my test on another attribut which is not encrypted. but yeah its a good point to know about the encryption.
    I also tried to use evaluators on internet and my expression looks good if i want to catch cases that i dont want in my password...
    as a reminder : (.)(\1)|(\d)
    So if i write :
    "1password"   >> result : true
    "password"     >> result : false
    "pppassword" >> result : true
    "password01" >> result : false
    "passwooord" >> result : false
    but finally if i put that expression in the field "regex" of my attribut, IDM never let me save my new password because it's not a "correct value".
    So im disapointed because i don't how to solve it in IDM but i feel like i found the good expression...
    Any another idea?
    Regards
    Jeremy

  • Extract the numbers in string using regex

    Hi,
    How to extract the numers in string using regex?.
    Already i tried split up the string using [\\s]
    For ex: "Uting Tatk and Window Panet 15"
    it gives the ans 15.
    if the string is
    For ex: "Uting Tatk and Window Panet 15 New!"
    i can't find the number.
    so plz give me some idea to get the number frm String.
    Thanks

    I am developing a java project to extract Table of
    content in a particular
    PDF.
    i extracted all topics.
    then i want 2 extract page number from dat extracted
    TOC.
    if the TOC ends with number then i can easily find
    out the number
    but in vain if the TOC ends with like this
    "Uting Tatk and Window Panet 15 New!".
    i could n't find the page number.What will you do if it says:
    "15 ways to find topics 42 new"

  • DW CS5 - Find/Replace using RegEx

    Hello, everyone.
    I am working on some inherited code, and the previous people used some named anchors; some are properly closed, most are not.  There are over 100 of them that I don't want to correct manually.
    Examples:
    <a name="this">
    <a name="that"></a>
    <a name="other">
    <a name="org"> </a> <-- notice the space between
    I am trying to use RegEx in the Find and Replace so I can correct these to all being closed.  Here is the string I'm looking for:
    <a name="([^"]*)["]>[^\w{1,}<\/a>]
    But this is not finding any of the named anchors.  I did have the same thing, minus the [^\w{1,}<\/a> part, but it found ALL the named anchors, closed and not-closed.
    Also, I have (for replacement) <a name="$1"/>, but am not sure if this will properly replace.  Suggestions?
    ^_^

    Anyone?

  • Validating input if nonalphanumeric character without using regex

    Hi Guys,
    I am trying to validate if the user input does not contain any alphanumeric characters such as (A-Z, a-z, 0-9)... The problem was solved through this forum by using regex....
    Unfortunately I'm developing with Blackberry (RIM IDE) but it seems that it doesn't support java.util.regex.Pattern and java.util.regex.Matcher;
    Is there any other solutions to this problem? Can java.util.regex.* be added to Blackberry JDE?
    If anybody knows any solution to this problem...Please let me know...
    Please help... Thanks in advance

    public boolean method(String s) {
        loop over String {
            if (current char is not a valid char) {
                return false;
        return true;
    }

  • Validate a number using regex

    I would like to validate numbers using regex, and thought that a search both here on the net would produce what I was looking for, but...
    The closest I can get to a number validation sequence (thankyou www.interviewjava.com) was the following:
    "^[-+]?[0-9]*\\.?[0-9]+$"
    but unfortunately it is incomplete. The explanation of the code is as follows:
    * ^[-+]? : Starts with an optional “+” or “-” sign. [0-9]* : May have
    * one or more digits. \\.? : May contain an optional “.” (decimal
    * point) character. [0-9]+$ : ends with numeric digit.
    Can anyone point me to a validation sequence that includes the comma for separating thousands? (The comma can appear multiple times, and is always followed by three digits).
    I'd be very grateful for any help on this. Thankyou.

    Thank you very much for your incredibly fast reply.
    Did you cook that up yourself in the seven minutes since I posted the question, or did you have it somewhere ready?

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Using RegEx in Subscription Criteria

    Using RegEx in Subscription Criteria
    Hello
    I want to use RegEx expression for filtering in my Subscription criteria, as follows:
    Let say all the monitor I created start with same set of characters i.e.
    "My Monitor"
    Therefore I have several monitors called
    My Monitor ABC
    My Monitor 123
    My Monitor XYZ
    Therefore as part of the Subscription Criteria, under "with a specific name" I currently have
    My Monitor%
    The % meaning any one or more characters. That works find I receive notifications for alerts from all of the monitors with the above names.
    Now what I want to do is keep this one subscription criteria but exclude notifications from say My Monitor 123. I still want to receive notifications from the other two monitors, therefore I was thinking this is a case for RegEx
    First question is can I use RegEx in the criteria "with a specific name" field? I guess I am already doing the with the % however, I believe that is an SQL expression rather than a true RegEx expression?
    The following blog has some detailed information
    http://social.technet.microsoft.com/Forums/en-US/operationsmanagergeneral/thread/ac0bf65f-f562-4f8c-b624-5fbe7ee2e795/
    I am not clear if this would work in my case, for example it states the ^ character is used to denote NOT. Based on this I was thinking about changing the above
    My Monitor%
    To
    My Monitor%[^123]
    Will the above work, is it the correct syntax?
    Any advise, most welcome
    Thanks you all
    Ernie

    Hello Yury,
    Thanks again for your help. Your solution worked, however with a slight difference as I discovered something else while testing.
    Basically the example above
    My Monitor [^1][^2][^3]%
    Only takes into account the First character of the word/phrase for example, using the above filer, the results were
    My Monitor ABC - pass
    My Monitor 123 - no pass
    My Monitor XYZ - pass
    My Monitor 222 - pass
    My Monitor XY3 - pass
    I therefore had to add an _ as part of the filter meaning one character, therefore using the above example if I want to block
    My Monitor 123
    My filter would be as follows
    My Monitor [^1][^_2][^__3]%
    i.e. 1 being the first character, 2 being the second character by placing any single character in front of it using the _ then 3 being the third character by placing and two characters
    in from of it by using two _ characters i.e. __
    Thanks again, I could not of figured it out without your help
    Ernie

  • Email address validation, is there a way to use Regex or other fuzzy searching?

    I would like to use PL/SQL for Email address validation, is there a way to use Regex (regular expressions) or some other fuzzy searching for that? Using % and _ wildcards only take you so far...
    I need something that will verify alphanumeric charectors (no ",'.:#@&*^ etc.) any ideas?
    Current code:
    if email not like '_%@_%.__%' or email like '%@%@%' or email like '% %' or email like '%"%' or email like '%''%' or email like '%
    %' then
    The last line is to make sure there are no linebreaks in the middle of the email address, is there a better way to signify a line break, like \n or an ascii equivilent?

    Michael:
    The as noted in the previous post, DBI is a Perl package that allows Perl to talk to various databases, including Oracle. We use DBI on several UNIX servers, and it does not require ODBC, and I have always found it to be extremely quick. Things may be different in the Windows world.
    If you are spooling files out to run through Perl anyway, you may want to take a look at DBI. You could probably modify your existing scripts to use DBI fairly easily. The basic structure using DBI is like:
    use DBI;
    my dbh;       # A database handle
    my sth;       # A statment handle
    my sqlstr;    # SQL statement
    my db_vars;   # Variables for your db columns
    # Connect to the database
    $dbh = DBI->connect( "dbi:Oracle:service_name","user/password");
    $sqlstr = 'SELECT * FROM emp WHERE id = ?' # even takes bind variables
    #Prepare statement
    $sth = $dbh->prepare($sqlstr);
    $sth->execute(12345);  # Execute with values for bind if desired
    # Walk the "cursor"
    while (($db_vars) = $sth->fetchrow_array()) {
       your processing here

  • Using Regex to search strings......

    Hey guys,
    I'm trying to scan an html file for specific strings. Basically, I just store the entire html file as a one big long string and then use a regex to scan the string for specific keywords that I am looking for. However, I am not all that familiar with regular expressions in java, and, although I have spent a considerable amount of time reading over the tutorials, I can't seem to get my regular expression to produce the results that I want.
    +More specifically, what I am trying to scan the html string for is a keyword preceded by a non-alphanumeric character([/W] and followed by a non-alphanumeric character. Also, since the keywords generally represent country names, state names, state abbreviations, city names, and the like.....I really want to make the scan case-insensitive to the case format of the keyword except in the case that the keyword is an abbreviation (i.e., CA, IN, NY,etc. since making this case-insensitive would pick up a lot of garbage, especially in cases like: IN)+_.* As of right now, this is what I am using for my regex(and the results are all over the place):
    *String regex = "[/W]+"+"(?i)"+keyword+"[/W]+";*
    This just seems wrong! I've played around with it and, lets just say, the results have generally gotten worse. Does anyone have any ideas on how I should correctly format the regex to achieve the goal explained above?? Any and all help would be greatly appreciated. Thanks.

    A technique I find very useful in writing complex regex's is to split the regex into its parts and work on just the one part at a time. This helps me to easily see that the components match exactly what I think I am matching. Once I have every individual part working it is very easy to join them to create the entire match.
    Something like...
    String keywordRegex = "";
    String nonAlphaCharRegex = "";
    //..etc. etc
    String fullRegex = keywordRegex + "whateverIwantToMatchBetween" + nonAlphaCharRegex + ...

Maybe you are looking for