请解释我为什么使用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发布于 2016-04-05 15:13:09
使用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'"https://stackoverflow.com/questions/36430170
复制相似问题