douyuan4825 2013-02-18 19:35
浏览 55
已采纳

将正则表达式代码从php转换为java无效

I'm trying to convert this code from PHP to Java and I cannot make it work identically:

PHP:

function check_syntax($str) {

    // define the grammar
    $number = "\d+(\.\d+)?";
    $ident  = "[a-z]\w*";
    $atom   = "[+-]?($number|$ident)";
    $op     = "[+*/-]";
    $sexpr  = "$atom($op$atom)*"; // simple expression

    // step1. remove whitespace
    $str = preg_replace('~\s+~', '', $str);

    // step2. repeatedly replace parenthetic expressions with 'x'
    $par = "~\($sexpr\)~";
    while(preg_match($par, $str))
        $str = preg_replace($par, 'x', $str);

    // step3. no more parens, the string must be simple expression
    return preg_match("~^$sexpr$~", $str);
}

Java:

private boolean validateExpressionSintax(String exp){

    String number="\\d+(\\.\\d+)?";
    String ident="[a-z]\\w*";
    String atom="[+-]?("+number+"|"+ident+")";
    String op="[+*/-]";
    String sexpr=atom+"("+op+""+atom+")*"; //simple expression

    // step1. remove whitespace
    String str=exp.replaceAll("\\s+", "");

    // step2. repeatedly replace parenthetic expressions with 'x'
    String par = "\\("+sexpr+"\\)";

    while(str.matches(par)){
        str =str.replace(par,"x");
    }

    // step3. no more parens, the string must be simple expression
    return str.matches("^"+sexpr+"$");
}

What am I doing wrong? I'm using the expression teste1*(teste2+teste3) And i'm getting a match in php code but not in the java one, the line while(str.matches(par)) fails at first try. I assume this must be some problem with the matches method?

  • 写回答

1条回答 默认 最新

  • douren2395 2013-02-18 19:51
    关注

    String.matches in Java will check that the whole string matches against the regex (as if the regex has ^ at the beginning and $ at the end).

    You need Matcher to find some text inside a string that matches some regex:

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(inputString);
    
    while (matcher.find()) {
        // Extract information from each match
    }
    

    In your case, since you are doing replacement:

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(inputString);
    
    StringBuffer replacedString = new StringBuffer();
    
    while (matcher.find()) {
        matcher.appendReplacement(replacedString, "x");
    }
    
    matcher.appendTail(replacedString);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?