Jay*_*ova -4 java search replace
这段代码有什么问题?
public int convert(String param){
System.out.println(param); // OUTPUT1
if(param=="NUM1"){
return 10;
}else if(param=="NUM2"){
return 20;
}else
return 0;
}
return param;
}
String Formula="[NUM1]+[NUM2]";
Formula = Formula.replaceAll("\\[(.*?)\\]", convert("$1") );
System.out.println(Formula); // OUTPUT2
//OUTPUT1 - $1
//OUTPUT2 - 0+0
Run Code Online (Sandbox Code Playgroud)
我希望OUTPUT1为(NUM1或NUM2),OUTPUT2为"10 + 20".
在Java中,不能仅仅用于"$1"
引用匹配表达式的部分内容,如脚本语言.而是使用捕获组.
您应该首先阅读Pattern的javadoc .
不是最好的事情:
String line = "[NUM1]+[NUM2]";
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(line);
while(m.find()) {
String token = m.group(1);
String newValue = convert(token);
line = line.replaceAll(token, newValue);
}
Run Code Online (Sandbox Code Playgroud)