我正在尝试将此代码从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);
}
爪哇:
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))
在第一次尝试失败。我认为匹配方法一定有问题吗?
答案 0 :(得分:2)
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);