[英]python re.findall vs re.sub
Please explain me why I get different results with using re.find and re.sub 请解释一下为什么使用re.find和re.sub会得到不同的结果
The string which I parse: 我解析的字符串:
GRANT USAGE ON *.* TO 'testuser'@'10.10.10.10' IDENTIFIED BY PASSWORD '*A78AF560CD6F8FEA4DC8205299927B6CB1B1F56A'
Code: 码:
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))
So I get what I want: 所以我得到了我想要的:
['testuser']
['10.10.10.10']
So, I want to change ip address and user, so I try to use re.sub 所以,我想更改IP地址和用户,所以我尝试使用re.sub
Code 码
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)
But I just get this: 但是我得到这个:
another_ip
another_user
With re.sub()
you need to specifically target which part of the string are you trying to substitute. 使用
re.sub()
您需要专门针对要替换的字符串部分。 In other words, re.sub()
would replace everything that was matched by a regular expression (well, strictly speaking , the leftmost non-overlapping occurrence of a pattern
) - in your case you are replacing the complete string. 换句话说,
re.sub()
会替换正则表达式匹配的所有内容( 严格来说 , the leftmost non-overlapping occurrence of a pattern
)-在您的情况下,您要替换完整的字符串。 Instead, you can match the user and the IP address specifically, for example: 而是可以具体匹配用户和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.