Domanda

I have a String and list of words. I want to search the each word in that string and replace that word with any shortcut like UPDATE DATABASE to UPD DB. Below are the list of words I need to look for

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.

This is my code ===>

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

I used if else if condition but I don't think that is a efficient way to code. Can any one please help me in this issue. I asked my friends about this they told me to use REGEX but I feel regex is complex for me to understand.

below is the answer for my case:

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);
            }
È stato utile?

Soluzione

Make sure to use replaceAll(). Also you could put all of the terms and replacements in an array.

Like so:

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

Altri suggerimenti

I might not have understood your question well but...
The String class in Java offers a "replace" method, use:

String newString = myString.replace("stringToReplace", "replacement");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top