How to replace special character and its next stri

2020-04-17 04:13发布

问题:

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

"alter table  $owner.$table_name ENABLE constraint $constraint_name;"

to

"alter table  hr.hr ENABLE constraint scma_constraint;"

回答1:

String.replace()

String myString = "...";
myString = myStrign
         .replace("$owner", "hr")
         .replace("$table_name", "hr")
         .replace("$constraint_name", "blah");


回答2:

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.



回答3:

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.



回答4:

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