用另一个String替换String的子字符串

时间:2012-08-13 00:18:00

标签: java string tokenize

我有一个字符串

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

我在下面的代码的帮助下进行了标记

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是任意的!

3 个答案:

答案 0 :(得分: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];

现在好了解释:

tokens = [a, b, c, d]
delimiters = [ "(" , " AND " , ") OR (" , " AND " , ") " ]

当迭代分隔符时,我们取“(”+“a”+“= 1”。

从那里我们有“(a = 1” + =“AND”+“b”+“= 1”。

然后:“(a = 1 AND b = 1” + =“)或(”+“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)”

答案 1 :(得分: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 AND b = 1)OR(c = 1 AND d = 1)

答案 2 :(得分:1)

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