考虑:
String str = (a AND b) OR (c AND d);
String[] tokened = [a, b, c, d]
String[] edited = [a=1, b=1, c=1, d=1]
简单:
for (int i=0; i<tokened.length; i++)
str.replaceAll(tokened[i], edited[i]);
编辑:
String addstr = "=1";
String str = "(a AND b) OR (c AND d) ";
String delims = "AND|OR|NOT|[!&|() ]+"; // Regular expression syntax
String[] tokens = str.trim().split(delims);
String[] delimiters = str.trim().split("[a-z]+"); //remove all lower case (these are the characters you wish to edit)
String newstr = "";
for (int i = 0; i < delimiters.length-1; i++)
newstr += delimiters[i] + tokens[i] + addstr;
newstr += delimiters[delimiters.length-1];
OK,现在的解释:
tokens = [a, b, c, d]
delimiters = [ "(" , " AND " , ") OR (" , " AND " , ") " ]
当通过分隔符迭代时,我们采取“(”+“a”+“= 1”。
从那里,我们有“(A = 1” + = “和” + “B” + “= 1”
而上:“(A = 1和B = 1” + =“)或(”+“c”+“= 1”。
再次:“(A = 1和B = 1)或(c = 1” + = “和” + “d” + “= 1”
最后(在for
循环之外): “(A = 1和b = 1)或(c = 1和d = 1” + = “)”
在那里,我们有:“(A = 1和b = 1)或(C = 1 AND d = 1)“
请不要在使用StringBuilder时使用StringBuffer。 – 2012-08-13 08:04:16
@PeterLawrey在这里可以使用StringBuilder吗? – Pshemo 2012-08-13 10:16:49