2012-08-13 149 views
2

我有一个字符串替换字符串的子字符串用另一个字符串

String str = (a AND b) OR (c AND d) 

我tokenise与代码的帮助下

String delims = "AND|OR|NOT|[!&|()]+"; // Regular expression syntax 
String newstr = str.replaceAll(delims, " "); 
String[] tokens = newstr.trim().split("[ ]+"); 

,并得到的String []下面

[a, b, c, d] 

对阵列的每个元素添加“= 1”,以便它变成

[a=1, b=1, c=1, d=1] 

现在我需要更换这些值的初始字符串使其

(a=1 AND b=1) OR (c=1 AND d=1) 

有人可以帮助或指导我?最初的String str是任意的!

回答

2

此答案是根据@Michael's idea(BIG +1为他)的搜索词只包含小写字母,并加入=1他们:)

String addstr = "=1"; 
String str = "(a AND b) OR (c AND d) "; 

StringBuffer sb = new StringBuffer(); 

Pattern pattern = Pattern.compile("[a-z]+"); 
Matcher m = pattern.matcher(str); 
while (m.find()) { 
    m.appendReplacement(sb, m.group() + addstr); 
} 
m.appendTail(sb); 
System.out.println(sb); 

输出

(A = 1和B = 1)或(c = 1和d = 1)

+0

请不要在使用StringBuilder时使用StringBuffer。 – 2012-08-13 08:04:16

+0

@PeterLawrey在这里可以使用StringBuilder吗? – Pshemo 2012-08-13 10:16:49

1

str允许多长时间?如果答案是“相对较短”,则可以简单地为数组中的每个元素执行“全部替换”。这显然不是性能最友好的解决方案,所以如果性能是一个问题,不同的解决方案将是需要的。

+0

我已经建立了阵!我只需要将替换的数组元素放回到初始字符串中。就像我想把[a = 1,b = 1,c = 1,d = 1]放入字符串(a AND B)或者(c AND d)来代替a,b,c,d。你明白我的意思吗? – Achilles 2012-08-13 00:32:43

+0

是的,我在说数组中的每个元素都是str.replaceAll(tokens [i],tokens [i] +“= 1”)。 – 2012-08-13 00:34:23

+0

@Pshemo提出了一个非常好的观点“但是如果str =”(A AND B)“?你会得到str =”(A = 1 A = 1ND B = 1)“ – Achilles 2012-08-13 00:50:05

2

考虑:

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)“

+1

您也可以跟踪找到所有标记的索引,并插入所需的字符串: – Michael 2012-08-13 00:37:02

+2

但是,如果'str =”(A AND B) ?你会得到'str =“(A = 1 A = 1ND B = 1)”' – Pshemo 2012-08-13 00:41:36

+0

我接受了这个评论后,我怎么能跟踪他们的索引tho?对不起 – Achilles 2012-08-13 00:42:34

相关问题