e[1] is equal to 192.168.1.1. I would like to add regular expression to this search to prevent a match against 192.168.11. Can anyone help? I have beat my h开发者_运维百科ead against this for a while. I get a syntax error if I try to append anything after the slice.
re.search(e[1], '192.168.1.11')
<_sre.SRE_Match object at 0x1004c2648>
Since e[1] is a string you can add to it with the '+' operator. For example, you can add r'\b'
to set a word boundary (note the raw string; without the 'r' prefix '\b' is a backspace):
>>> e = ['', '192.168.1.1']
>>> pattern = r'\b' + re.escape(e[1]) + r'\b' #remember to escape e[1]
>>> re.search(pattern, '192.168.1.11')
>>> re.search(pattern, '192.168.1.1spam')
>>> re.search(pattern, '192.168.1.1').group()
'192.168.1.1'
>>> re.search(pattern, 'spam 192.168.1.1 eggs').group()
'192.168.1.1'
>>> string = '192.168.1.1,192.168.1.11,192.168.1.1'
>>> [x.group() for x in re.finditer(pattern, string)]
['192.168.1.1', '192.168.1.1']
精彩评论