【问题标题】:Converting regex code from php to java not working将正则表达式代码从 php 转换为 java 不起作用
【发布时间】:2013-02-03 08:04:25
【问题描述】:

我正在尝试将此代码从 PHP 转换为 Java,但我无法使其工作相同:

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+"$");
}

我做错了什么?我正在使用表达式 teste1*(teste2+teste3) 我在 php 代码中得到匹配,但在 java 中没有,while(str.matches(par)) 行第一次尝试失败。我想这一定是matches方法的问题?

【问题讨论】:

    标签: java php regex converter


    【解决方案1】:

    Java 中的String.matches 将检查整个字符串是否与正则表达式匹配(就好像正则表达式的开头有^,结尾有$)。

    您需要Matcher 才能在字符串中找到与某些正则表达式匹配的文本:

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

    在你的情况下,因为你正在更换:

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(inputString);
    
    StringBuffer replacedString = new StringBuffer();
    
    while (matcher.find()) {
        matcher.appendReplacement(replacedString, "x");
    }
    
    matcher.appendTail(replacedString);
    

    【讨论】:

    • 不理解replacedString stringbuffer,inputString去哪里了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2016-04-02
    • 2013-06-26
    相关资源
    最近更新 更多