修改SQL语句的字符串输出

时间:2013-12-13 21:51:03

标签: java regex

我正在尝试修改此[SNO, text, SNAME, text, STATUS, number, CITY, text]之类的输出。 对于这样的事情(SNO text, SNAME, text, STATUS number, CITY, text)

但是在使用此代码处理第一个提到的输出后得到的输入

String fieldsToTable ="(" + tableFields + ")";
fieldsToTable.replaceAll("[()]", "");
String modFieldsToTable = fieldsToTable.replace("\\,","");
System.out.println(modFieldsToTable);

我将其作为输出结果:([SNO, text, SNAME, text, STATUS, number, CITY, text])

我认为我并没有真正掌握正则表达式的概念......

4 个答案:

答案 0 :(得分:0)

你试过这个吗?

fieldsToTable = fieldsToTable.replace("[","(").replace("]",")");

答案 1 :(得分:0)

这个怎么样?

String fields = "(" + tableFields.substring(1, tableFields.length() - 1) + ")";

答案 2 :(得分:0)

尝试下一个:

public static void main(final String[] args) {
    String tableFields = "[SNO, text, SNAME, text, STATUS, number, CITY, text]";
    List<String> list = new ArrayList<String>();
    for (String field : tableFields.split("[\\[\\] ,]")) {
        if (!field.isEmpty()) {
            list.add(field);
        }
    }
    StringBuilder sb = new StringBuilder("(");
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        sb.append(iterator.next());
        if (iterator.hasNext()) {
            sb.append(",");
        }
    }
    sb.append(")");
    String modFieldsToTable = sb.toString();
    System.out.println(modFieldsToTable);
}

答案 3 :(得分:0)

给定输入String tableFields = "[SNO, text, SNAME, text, STATUS, number, CITY, text]" ...

要删除方括号,请尝试:

String fieldsToTable = tableFields.replace('[', '('); // replaces [ with (  
fieldsToTable = fieldsToTable.replace(']', ')');      // replaces ] with )


目前尚不清楚何时删除您的逗号。如果要删除所有逗号,代码将为:

fieldsToTable = fieldsToTable.replaceAll(",", ""); // removes all commas

如果您只想在这两种特定情况下删除逗号,则可以执行以下操作:

fieldsToTable = fieldsToTable.replace("SNO,", "SNO");      // removes comma after SNO
fieldsToTable = fieldsToTable.replace("STATUS," "STATUS"); // removes comma after STATUS


请注意,由于replace方法返回结果字符串,因此可以通过将三者链接在一起来提高代码的清晰度。

String fieldsToTable = tableFields.replace('[', '(')
                                  .replace(']', ')')
                                  .replaceAll(",", "");

String fieldsToTable = tableFields.replace('[', '(')
                                  .replace(']', ')')
                                  .replace("SNO,", "SNO")
                                  .replace("STATUS," "STATUS");