在python 3中,我有一個字串:
CONN <DO_NOT_PRINT>user</DO_NOT_PRINT>/<DO_NOT_PRINT>password</DO_NOT_PRINT>@//host:port/service
我想用星號替換 <DO_NOT_PRINT> 和 </DO_NOT_PRINT> 標簽之間的單詞中的每個字母(并洗掉標簽),即:
CONN ****/********@//host:port/service
字串用戶,尤其是密碼可以是任何字符
到目前為止我所擁有的是:
z="CONN <DO_NOT_PRINT>user</DO_NOT_PRINT>/<DO_NOT_PRINT>password</DO_NOT_PRINT>@//host:port/service"
REPLACEME = re.compile('<DO_NOT_PRINT>(. )<\/DO_NOT_PRINT>')
found = REPLACEME.search(z)
print(found)
if found:
old_text = found.group(1)
new_z = z.replace(old_text, '*' * len(old_text))
print(new_z)
else:
print(z)
但它在列印時無法正常作業:
CONN <DO_NOT_PRINT>******************************************</DO_NOT_PRINT>@//host:port/service
代替 :
CONN ****/********@//host:port/service
uj5u.com熱心網友回復:
正則運算式嘗試與可能的最長值匹配,因此(. )捕獲:
user</DO_NOT_PRINT>/<DO_NOT_PRINT>password
您應該在加號后指定非貪婪運算子:
REPLACEME = re.compile('<DO_NOT_PRINT>(. ?)<\/DO_NOT_PRINT>')
你的group(1)不包括<DO_NOT_PRINT>。如果您希望它也消失,請使用group(0)獲取整個匹配的字串。嘗試:
z.replace(found.group(0), '*' * len(old_text))
編輯:
如果你想替換多次出現,你可以使用re.finditer()并.replace()為每個匹配做一個:https : //docs.python.org/3/library/re.html#re.finditer
import re
z="CONN <DO_NOT_PRINT>user</DO_NOT_PRINT>/<DO_NOT_PRINT>password</DO_NOT_PRINT>@//host:port/service"
REPLACEME = re.compile('<DO_NOT_PRINT>(. ?)<\/DO_NOT_PRINT>')
founds = REPLACEME.finditer(z)
print(founds)
for found in founds:
old_text = found.group(1)
z = z.replace(found.group(0), '*' * len(old_text))
print(z)
或者,使用看起來更優雅的 Viktor 的答案。
uj5u.com熱心網友回復:
您可以使用
import re
z="CONN <DO_NOT_PRINT>user</DO_NOT_PRINT>/<DO_NOT_PRINT>password</DO_NOT_PRINT>@//host:port/service"
REPLACEME = re.compile('<DO_NOT_PRINT>(.*?)</DO_NOT_PRINT>', re.DOTALL)
print( REPLACEME.sub(lambda x: '*' * len(x.group(1)), z) )
# => CONN ****/********@//host:port/service
請參閱Python 演示。
注意事項:
re.compile(r'<DO_NOT_PRINT>(.*?)</DO_NOT_PRINT>', re.DOTALL)-*?惰性量詞用于確保匹配在右側分隔符的最左邊出現并re.DOTALL確保.匹配換行符lambda x: '*' * len(x.group(1))現在是re.sub替換引數,其中x是MatchData物件,x.group(1)是第 1 組捕獲的值,兩個字串之間的文本。
如果您關心性能,請展開惰性點模式:
REPLACEME = re.compile(r'<DO_NOT_PRINT>([^<]*(?:<(?!/DO_NOT_PRINT>)[^<]*)*)</DO_NOT_PRINT>')
不要re.DOTALL在這里使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316141.html
