I have a string like below. Here, I want to replace just next immediate word after a particular word like, '%(db_user)s' and '%(db_passsword)s' but the words I can search for in the string are --db-user and --db-passwords becuase the above will be substituted by values.
Input:
"cd scripts && bash setup.sh --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '%(db_user)s' --db-password '%(db_password)s' "
Output:
"cd scripts && bash setup.sh --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '***' --db-password '****' "
So please help me with a function where I will provide an array of words and a string, which will replace next words to those supplied words.
This will help -
import re
def char_index(sentence, word_index):
sentence = re.split('(\s)',sentence) #Parentheses keep split characters
return len(''.join(sentence[:word_index*2]))
def print_secure_message(msg):
secure_words = ['--db-user', '--db-password']
# Removing extra white spaces within string
msg = re.sub(' +', ' ', msg)
cpy_msg = msg.split(" ")
for word in secure_words:
# Getting index of the word's first characters
t = re.search(word, msg)
# Getting index of the next word of the searched word's
word_index = cpy_msg.index(word)+2;
index= char_index(msg, word_index)
print(t.end(), word_index, index)
msg = msg[0:t.end() + 1] + "'****'" + msg[index - 1:]
print(''.join(msg))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With