[英]python re.findall vs re.sub
請解釋一下為什么使用re.find和re.sub會得到不同的結果
我解析的字符串:
GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'
碼:
import re
S="GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'"
U=re.compile(r'.* TO \'(.*?)\'@.*')
H=re.compile(r'.*\'@\'(.*?)\'.*')
print(U.findall(S))
print(H.findall(S))
所以我得到了我想要的:
['testuser']
['10.10.10.10']
所以,我想更改IP地址和用戶,所以我嘗試使用re.sub
碼
import re
S="GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'"
U=re.compile(r'.* TO \'(.*?)\'@.*')
H=re.compile(r'.*\'@\'(.*?)\'.*')
HOST=H.sub('another_ip',S)
USER=U.sub('another_user',S)
print(HOST)
print(USER)
但是我得到這個:
another_ip
another_user
使用re.sub()
您需要專門針對要替換的字符串部分。 換句話說, re.sub()
會替換正則表達式匹配的所有內容( 嚴格來說 , the leftmost non-overlapping occurrence of a pattern
)-在您的情況下,您要替換完整的字符串。 而是可以具體匹配用戶和IP地址,例如:
>>> re.sub(r"'(\w+)'@'(\d+\.\d+\.\d+\.\d+)'", "'another_user'@'another_ip'", S)
"GRANT USAGE ON *.* TO 'another_user'@'another_ip' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.