【问题标题】:Regex double operators are single counting正则表达式双运算符是单计数
【发布时间】:2019-02-27 20:33:56
【问题描述】:

我想检查是否有双重运算符。例如:

int 结果 = x+y;

结果为@​​987654321@,它正在工作。但是:

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--;
    }
}

【问题讨论】:

  • 您好,欢迎来到 SO,您能否添加更多关于问题所在的说明。 x+y 的运算符计数是 2 吗?
  • 你好,(=) 1 运算符 (+) 1 运算符 2 运算符。我正在寻找所有的运营商。这里没问题。问题双运营商。正在数2次。例如:(==) 等于。但是正则表达式计算了两次。我想数一次。
  • 你也想匹配 (+) 和 (++) 对吗?
  • String doubleOperatorPatternString = "['==''++''--''&&''||']";模式 doubleOperatorPattern = Pattern.compile(doubleOperatorPatternString);匹配器 doubleOperatorMatcher = doubleOperatorPattern.matcher(file); while(doubleOperatorMatcher.find()){ operatorCounter--; }
  • 你可以编辑问题并格式化代码

标签: java regex double operator-keyword


【解决方案1】:

您可以先定义++ 和其他两个字符运算符,例如+=-=,然后再定义单个字符运算符+-=。如果我们遵循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);

但它会找到 &lt;++ 并打印 2。

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

【讨论】:

  • 这样更好: Pattern pattern = Pattern.compile("\\+\\+|--|\\+\\+|&&|\\+\\+|==|\ \||\\\\instanceof");非常感谢。该文件帮助了我。它现在正在工作。
  • @MuhammetÖmer 添加了文档中的其他运算符,这是一个怪物正则表达式,因此添加了 cmets。如果有帮助,请采纳答案。
猜你喜欢
  • 2012-10-30
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
相关资源
最近更新 更多