简体   繁体   English

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

[英]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转换为Java,但我不能使它的工作方式相同:

PHP: 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: 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. 我正在使用表达式teste1*(teste2+teste3)而且我在PHP代码中得到一个匹配但在java中没有匹配, while(str.matches(par))第一次尝试while(str.matches(par))失败了。 I assume this must be some problem with the matches method? 我认为这必须是匹配方法的一些问题?

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). Java中的String.matches将检查整个字符串是否与正则表达式匹配(就像正则表达式在开头有^而在结尾有$ )。

You need Matcher to find some text inside a string that matches some regex: 你需要Matcher在匹配某些正则表达式的字符串中找到一些文本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM