为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

青春有我 2022-07-14 10:18:58
我想检查是否有双重运算符。例如 :整数结果 = 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 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

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


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


查看完整回答
反对 回复 2022-07-14
  • 1 回答
  • 0 关注
  • 118 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号