Maxrunner
Maxrunner

Reputation: 1965

Converting regex code from php to java not working

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?

Upvotes: 0

Views: 906

Answers (1)

nhahtdh
nhahtdh

Reputation: 56829

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

Upvotes: 2

Related Questions