-6

我有一个字符串和单词列表。我想搜索该字符串中的每个单词并将该单词替换为任何快捷方式,例如将 UPDATE DATABASE 更新为 UPD DB。以下是我需要查找的单词列表

更改数据库、更改表、更改视图、创建数据库、创建过程、创建模式、创建表、创建视图、删除、删除数据库、删除过程、删除表、删除视图、更新数据库。

这是我的代码 ===>

   if(payloadStr.contains("UPDATE DATABASE")){ 
payloadStr = payloadStr.replace("UPDATE DATABASE","UPD DB"); 
} else if(payloadStr.contains("ALTER DATABASE")) { 
payloadStr = payloadStr.replace("ALTER DATABASE", "ALTR DB"); 
}

我使用了 if else if 条件,但我认为这不是一种有效的编码方式。任何人都可以在这个问题上帮助我。我问过我的朋友,他们告诉我使用正则表达式,但我觉得正则表达式对我来说理解起来很复杂。

以下是我的案例的答案:

String[] words = { "UPDATE DATABASE", "ALTER DATABASE",
                    "ALTER TABLE", "ALTER VIEW", "CREATE DATABASE",
                    "CREATE PROCEDURE", "CREATE SCHEMA", "CREATE TABLE",
                    "CREATE VIEW", "DELETE FROM", "DROP DATABASE",
                    "DROP PROCEDURE", "DROP TABLE", "DROP VIEW" };

            String[] replaceWith = { "UPD DB", "ALTR DB", "ALTR TBL",
                    "ALTR VW", "CRT DB", "CRT PRCR", "CRT SCHM", "CRT TBL",
                    "CRT VW", "DEL FRM", "DRP DB", "DROP PRCR", "DRP TBL",
                    "DRP VW" };

            for (int i = 0; i < words.length; i++) {

                payloadStr = payloadStr.replaceAll(words[i], replaceWith[i]);
                getLogger().debug(
                        "SQL Statement in Message. Message Modified To Avoid Layer-7 Rejection:  "
                                + payloadStr);
            }
4

2 回答 2

1

我可能不太了解您的问题,但是...
Java 中的 String 类提供了一种“替换”方法,请使用:

String newString = myString.replace("stringToReplace", "replacement");
于 2013-05-02T19:02:02.020 回答
1

确保使用replaceAll(). 您也可以将所有术语和替换项放在一个数组中。

像这样:

String text = "ALTER DATABASE, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE";

String[] terms = {ALTER DATABASE, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE};

String[] replaceWith = {"","","","","","",""}; // whatever you replace with

for(int i = 0; i < terms; i++) {
    // may want to account for uppercase/lower case here too
    text = text.replaceAll(terms[i],replaceWith[i]);
}
于 2013-05-02T19:12:14.833 回答