How to replace special character and its next string with one string

前端 未结 4 1674
无人共我
无人共我 2021-01-22 16:30

How to replace the special character $owner with \"hr\" and $table_name with \"hr\" and $constraint_name with \"scma_constraint\" in dynamic. Change

\"alter ta         


        
相关标签:
4条回答
  • 2021-01-22 16:40

    The replaceAll method on String should do the trick. First store all the key-value pairs in a Map and then do something as follows:

    for each entry in the map
        myString.replaceAll(entry.key, entry.value)
    

    Should be straigtforward to implement.

    0 讨论(0)
  • 2021-01-22 16:49

    If you want to replace all matches, then use replaceAll() method and you need to escape special characters like dollar because replaceAll() gets a regex as first parameter and if you write "$owner" it will mean that your string must start with "owner".

    myString.replaceAll("\\$owner", "hr")
    .replaceAll("\\$table_name", "hr")
    .replaceAll("\\$constraint_name", "scma_constraint" );
    
    0 讨论(0)
  • 2021-01-22 17:00

    String.replace()

    String myString = "...";
    myString = myStrign
             .replace("$owner", "hr")
             .replace("$table_name", "hr")
             .replace("$constraint_name", "blah");
    
    0 讨论(0)
  • 2021-01-22 17:04

    Not sure that what you want but :

    String str = "alter table $owner.$table_name ENABLE constraint $constraint_name;"
    str = str.replace("$owner", "hr")
        .replace("$table_name", "hr")
        .replace("$constraint_name", "scma_constraint");
    

    The Javadoc is available here.

    The replace() method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar (without the support of regexp)

    The replaceAll() method does the same, but with the support of regexp.

    If needed, edit your question with more precision on what you want.

    0 讨论(0)
提交回复
热议问题