正则表达式不会用边界条件替换完全匹配

时间:2018-06-21 14:49:12

标签: regex python-3.x

我正在尝试使正则表达式很像bash中的sed命令。替换“ user-services-http”的完全匹配项,但是在“ user-services-http-two”也可以存在的情况下可以替换。

>>> f = "'value: http://ec2-35-171-57-57.compute-1.amazonaws.com:32370ssoeproxy/logout    value: http://ec2-35-171-57-57.compute-1.amazonaws.com:user-services-http-two/ssoeproxy/logout  value: user-services-http #458930'"
>>> re.sub(r'\buser-services-http$', '11111', f)'value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:user-services-http/ssoeproxy/logout    value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:user-services-http-two/ssoeproxy/logout'
>>> re.sub(r'\buser-services-http\b', '11111', f)
'value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:11111/ssoeproxy/logout    value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:11111-two/ssoeproxy/logout'

1 个答案:

答案 0 :(得分:0)

您可以像这样使用否定的外观:

import re

f = "value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:user-services-http/ssoeproxy/logout    value: http://ec2-xxx-xx-xxx-xxx.compute-1.amazonaws.com:user-services-http-two/ssoeproxy/logout"
print(re.sub(r'\buser-services-http\b(?!-[^/]+)/', '11111', f)

输出:

value: http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:11111/ssoeproxy/logout
value: http://ec2-xxx-xx-xxx-xxx.compute-1.amazonaws.com:user-services-http-two/ssoeproxy/logout

为确保没有后跟-two或其他字词。这可以通过使用否定字符类[^/]+完成。尝试这种方法的好地方是:

http://regex101.com