Java шаблон регулярных выражений в операциях - PullRequest
0 голосов
/ 23 апреля 2020

Что такое шаблон регулярного выражения для всех операторов в java

Я пытаюсь создать программу, которая вычисляет вес, когда эти операторы используются

операторы +, - , /,%, ++, -, ==, =,>, <, <=,> =, &&, ||,, |!, ^, ~, <<, >>, <<< >>>, .-> ::, + =, - =, =, / =, = >>> =, | = & =,% =, << =, >> =, ^ =

Я попробовал это ((\\-)(\\*)\((\\+)(\\%)(\\++)(\\--)(\\==)(\\!=)(\\>)(\\<)(\\>=)(\\<=)(\\&&)(\\|)(\\!)(\\^)(\\~)(\\<<)(\\>>)(\\>>>)(\\<<<)(\\,)(\\->)(\\.)(\\::)(\\+=)(\\-=)(\\*=))

String logicalC = "((\\-)(\*)((\\+)(\\%)(\\++)(\\--)(\\==)(\\!=)(\\>)(\\<)(\\>=)(\\<=)(\\&&)(\\|)(\\!)(\\^)(\\~)(\\<<)(\\>>)(\\>>>)(\\<<<)(\\,)(\\->)(\\.)(\\::)(\\+=)(\\-=)(\*=))";

, но это не сработало, никаких ошибок не произошло, но это не дало мне ожидаемых результатов. вывод был равен 0, он не учитывал количество операторов в коде.

это класс

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ControlStructure {

    ArrayList<String> line;
    ArrayList<Integer> ctcsCount;
    // S = no white space, s= white space
    // Check if condition
    //String conditionalC = "((?<!\\S)(if\\s*\\())";

    // Check for, while, doWhile condition
    //String iterativeC = "((?<!\\S)(for\\s*\\())|(while\\s*\\(.*\\)\\s*(?!\\s*;)|do\\s*\\{|do\\s*(?!.))";

    // Check switch statement
    //String switchC = "((?<!\\S)(switch\\s*\\())";

    // Check case statement
    //String caseC = "((?<!\\S)(case\\s+.*\\:|default\\s*\\:))";

    // Check catch statement
    // String catchC = "((?<!\\S)(catch\\s*\\())";

    // Check logical operators
     String logicalC = "([+,-,*,/,%,++,--,==,!=,>,<,<=,>=])";
     String keyword = "(\\bpublic|void\\b|true\\b|else\\b|default\\b|return\\b|null\\b|break\\b|this\\b)";

     //String logicalC = "[0-9]";



    // Check bitwise operators
    // String bitwiseC = "(\\|\\&)";

    public ControlStructure(ArrayList<String> lines) {
        this.line = lines;
        ctcsCount = new ArrayList<Integer>(lines.size());
    }

    // add 2 for condition
    /*
     * public int conditionCount(String line) { Pattern p1 =
     * Pattern.compile(conditionalC); Matcher m1 = p1.matcher(line);
     * 
     * int addCount = 0;
     * 
     * while (m1.find()) {
     * 
     * addCount = addCount + 2; } return addCount; }
     * 
     * // add 3 for iterative public int iterativeCount(String line) { Pattern p1 =
     * Pattern.compile(iterativeC); Matcher m1 = p1.matcher(line);
     * 
     * int addCount = 0;
     * 
     * while (m1.find()) {
     * 
     * addCount = addCount + 3; } return addCount; }
     * 
     * // add 2 for switch public int switchCount(String line) { Pattern p1 =
     * Pattern.compile(switchC); Matcher m1 = p1.matcher(line);
     * 
     * int addCount = 0;
     * 
     * while (m1.find()) {
     * 
     * addCount = addCount + 2; } return addCount; }
     * 
     * // add 1 for case public int caseCount(String line) { Pattern p1 =
     * Pattern.compile(caseC); Matcher m1 = p1.matcher(line);
     * 
     * int addCount = 0;
     * 
     * while (m1.find()) {
     * 
     * addCount++; } return addCount; }
     */


    public int conditionCount(String line) {
        Pattern p1 = Pattern.compile(logicalC);
        Matcher m1 = p1.matcher(line);

        int addCount = 0;

        while (m1.find()) {

            addCount = addCount + 1;
        }
        return addCount;
    }
    public int conditionCount2(String line) {
        Pattern p1 = Pattern.compile(keyword);
        Matcher m1 = p1.matcher(line);

        int addCount = 0;

        while (m1.find()) {

            addCount = addCount + 1;
        }
        return addCount;
    }
    // calc ctcs for a line
    public int calcline(String lines) {
        int conditionCount = conditionCount(lines);
        int iterativeCount = conditionCount2(lines);
        //int switchCount = switchCount(lines);
        //int caseCount = caseCount(lines);

        //return (conditionCount + iterativeCount + switchCount + caseCount);
        return (conditionCount + iterativeCount);

    }

    // calc ctcs for line by line
    public void calclinebyline() {
        for (int i = 0; i < line.size(); i++) {
            int conditionCount = conditionCount(line.get(i));
            int iterativeCount = conditionCount2(line.get(i));
            //int switchCount = switchCount(line.get(i));
            //int caseCount = caseCount(line.get(i));

            //ctcsCount.add(conditionCount + iterativeCount + switchCount + caseCount);
            ctcsCount.add(conditionCount + iterativeCount);
        }
    }

    // return ctcs for line
    public ArrayList<Integer> ctcsline() {
        calclinebyline();
        return ctcsCount;
    }

    // calc ctcs
    public int calcCtcs() {
        int totalctcs = 0;
        int i;
        for (i = 0; i < ctcsCount.size(); i++) {
            totalctcs = totalctcs + ctcsCount.get(i);
        }

        return totalctcs;
    }

}

Основной метод

 public class codeMain {

        public static void main(String[] args) throws IOException {

            String lines;
            ArrayList<String> line = new ArrayList<>();
            String documentName = "D:\\Downloads\\first.java";
            int addcount = 0;
            int i;

            // add document
            FileReader document = new FileReader(documentName);

            // read document
            BufferedReader br = new BufferedReader(document);

            while ((lines = br.readLine()) != null) {
                line.add(lines);
            }
            ControlStructure ctcs = new ControlStructure(line);

            ArrayList<Integer> ctcsCount = ctcs.ctcsline();

            System.out.println("");

            for (i = 0; i < line.size(); i++) {
                System.out.println("Line Number " + (i + 1) + " WTC * NC = " + ctcsCount.get(i));
            }

            System.out.println("Total CCS count = " + ctcs.calcCtcs());
            System.out.println("");
        }

    }

1 Ответ

0 голосов
/ 23 апреля 2020

Просто используйте чередование (регулярное выражение OR), обозначенное |:

(?:\+|-|\*|/|%|\+\+|--|==|!=|>|<|<=|>=)

(?:...) - это группа без захвата.

Также помните о метасимволах, таких как + или *, которые необходимо экранировать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...