Двойные операторы Regex имеют одинарный счет - PullRequest
0 голосов
/ 27 февраля 2019

Я хочу проверить, есть ли двойной оператор.Например:

int result = x + y;

приводит к operatorCounter = 2, это работает.Но:

for(;i<size;i++)

приводит к operatorCounter = 3, тогда как должно быть operatorCounter = 2.

Мое регулярное выражение String doubleOperatorPattern = "\'.\\++\'";

Операторы, которые я хочу: (++) (-) (==) (&&) (||)

public void findOperator(String file){
    String operatorPattern = "['+''-''*''/''=''<''>''<=''>=''&''|''^''!''\\-?']";
    Pattern pattern = Pattern.compile(operatorPattern);
    Matcher matcher = pattern.matcher(file);
    while (matcher.find()) {
        operatorCounter++;
    }
    String doubleOperatorPatternString = "['==''++''--''&&''||']";
    Pattern doubleOperatorPattern = 
    Pattern.compile(doubleOperatorPatternString);
    Matcher doubleOperatorMatcher = doubleOperatorPattern.matcher(file);
    while(doubleOperatorMatcher.find()){
        operatorCounter--;
    }
}

1 Ответ

0 голосов
/ 28 февраля 2019

Вы можете определить операторы ++ и другие два символа, такие как += или -=, прежде чем операторы с одним символом +, - и =.Если мы следуем Документам операторов и добавляем все операторы Java, регулярное выражение становится неприятным из-за экранирования:

Pattern pattern = Pattern.compile(
        "\\+\\+|--|" +          // ++ --
        "\\+=|-=|\\*=|" +       // += -= *=
        "/=|%=|&=|\\^=|" +      // /= %= &= ^=
        "\\|=|<<=|>>>=|>>=|" +  // |= <<= >>>= >>=
        "<<|>>>|>>|" +          // << >>> >>
        "==|!=|<=|>=|" +        // == != <= >=
        "&&|\\|\\||" +          // && ||
        "\\+|-|~|!|" +          // + - ~ !
        "\\*|/|%|" +            // * / %
        "\\+|&|\\^|\\||" +      // + & ^ |
        "<|>|=|" +              // < > =
        "instanceof"            // instanceof
);

Matcher matcher = pattern.matcher("for(;i<size;i++)");
int count = 0;
while (matcher.find()) {
  count++;
}
System.out.println(count);

, но оно найдет < и ++ и выведет 2.

Обратите внимание, что это регулярное выражение по-прежнему не поддерживает троичный оператор ? :.

...