搜索关键字并将其替换为缩写

时间:2013-05-02 18:57:06

标签: java regex replace contain

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

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,UPDATE DATABASE。

这是我的代码===>

   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条件,但我不认为这是一种有效的编码方式。任何人都可以帮我解决这个问题。我问我的朋友他们告诉我使用REGEX,但我觉得正则表达式对我来说很复杂。

下面是我的答案:

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);
            }

2 个答案:

答案 0 :(得分:1)

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

String newString = myString.replace("stringToReplace", "replacement");

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