2

我有一个字符串

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

4

3 回答 3

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

于 2012-08-13T00:36:19.207 回答
2

这个答案基于@Michael 的想法(对他来说是 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) 或 (c=1 AND d=1)

于 2012-08-13T02:20:37.783 回答
1

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

于 2012-08-13T00:29:06.303 回答