与えられた:
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];
さて、説明:
tokens = [a, b, c, d]
delimiters = [ "(" , " AND " , ") OR (" , " AND " , ") " ]
区切り文字を繰り返すときは、"(" + "a" + "=1" を取ります。
そこから、"(a=1" += "AND " + "b" + "=1" が得られます。
そして、「(a=1 AND b=1" += ") OR (" + "c" + "=1".
再び : "(a=1 AND b=1) OR (c=1" += " AND " + "d" + "=1"
最後に (for
ループ外): "(a=1 AND b=1) OR (c=1 AND d=1" += ")"
「 ( a=1 AND b=1) OR (c=1 AND d=1)」