3个回答

javascript:

``````     var reg = /^[A-Za-z]/;
var s = 'A+AA+AB*A+C';
console.log(s.replace(reg, 2));
s = 'M*Math.pow(M,2)';
console.log(s.replace(reg, 2));
``````

java:
public static void main(String[] args) {
String reg = "^[A-Za-z]";
String s = "A+AA+AB*A+C";
s = s.replaceAll(reg, "2");
System.out.println(s);
s = "M*Math.pow(M,2)";
s = s.replaceAll(reg, "2");
System.out.println(s);
}

wyzdeng 您的结果是 2+AA+AB*A+C 2*Math.pow(M,2) 但是期望结果是 2+AA+AB*2+C 2*Math.pow(2,2)

2+AA+AB*A+C
2*Math.pow(M,2)

2+AA+AB*2+C
2*Math.pow(2,2)

javascript：

`````` function replaceMe(orig, replaceChar, replaceValue) {
var reg_head = new RegExp('^' + replaceChar + '([\\+\\-\\*\\\\])');
var reg_middle = new RegExp('([\\+\\-\\*\\\\\\(])' + replaceChar + '([\\+\\-\\*\\\\\\),])', 'g');
var reg_end = new RegExp('([\\+\\-\\*\\\\])' + replaceChar + '\$');
return orig.replace(reg_head, replaceValue + '\$1').replace(reg_middle, '\$1' + replaceValue + '\$2').replace(reg_end, '\$1' + replaceValue);
}
console.log(replaceMe('A+AA+AB*A+C', 'A', 2));
console.log(replaceMe('M*Math.pow(M,2)', 'M', 2));
``````

java:

`````` /**
*
* @param orig  -- 为空会抛出空指针异常
* @param replaceChar
* @param replaceValue
* @return
*/
public static String getReplaceCalc(String orig, String replaceChar, String replaceValue) {
return orig.replaceAll("^" + replaceChar + "([\\*\\+\\-\\*\\\\])", replaceValue + "\$1")
.replaceAll("([\\+\\-\\*\\\\\\(])" + replaceChar + "([\\+\\-\\*\\\\\\),])","\$1" + replaceValue + "\$2")
.replaceAll("([\\+\\-\\*\\\\])" + replaceChar + "\$", "\$1" + replaceValue)
;
}

public static void main(String[] args) {
System.out.println(getReplaceCalc("A+AA+AB*A+C", "A", "2"));
System.out.println(getReplaceCalc("M*Math.pow(M,2)", "M", "2"));
System.out.println(getReplaceCalc("A+AA+AB*A+C", "C", "5"));
System.out.println(getReplaceCalc("M*Math.pow(M,2)", "M", "4"));
}
``````