请解释一下为什么使用 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()
将替换与正则表达式匹配的所有内容(strictly speaking,模式最左边的非重叠出现
) - 在你的情况下,你正在替换整个字符串。相反,您可以专门匹配用户和 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'"
关于python re.findall 与 re.sub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36430170/