python re.findall 与 re.sub

标签 python regex

请解释一下为什么使用 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/

相关文章:

python - 表示 float 的字符串

python - 计算字符串中给出的电路的总电阻

python - 在 python 中解析 pip list/pip freeze 的输出

java - Java 正则表达式的另一种模式

python - 使用selenium和python通过CssSelector的 "begins with"方法定位元素

python - Youtube API 错误 v3 - 'No Filter Selected'

javascript - 使用正则表达式删除点也会删除 *

xml 正则表达式/正则表达式 OR 运算符

在一行中多次使用相同模式的正则表达式

javascript - 为什么正向lookbehinds被捕获作为javascript中正则表达式匹配的一部分?