0

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?

0

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Not understanding the replacedString stringbuffer, where does the inputString goes to?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.