正则表达式双精度运算符是单计数

问题描述 投票:-2回答:1

我想检查是否有双重操作符。例如 :

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--;
    }
}
java regex double operator-keyword
1个回答
0
投票

您可以在单个字符运算符+++=-=之前定义+和其他两个字符运算符,如-=。如果我们关注Operators docs并添加所有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。

请注意,此正则表达式仍然不支持三元运算符? :

© www.soinside.com 2019 - 2024. All rights reserved.