In Python, How do you prevent partial matches using re.search if you are using a dictionary key as your pattern
How do you preve开发者_Python百科nt parital matches while using re.search if you are using a dictionary key as your pattern in Python. For this question I would like to avoid iterating through the nested list in the dictionary value. I've tried appending regular expressions to the search pattern but it results in error.
Partial Match:
>>> d
{'server': '192.168.1.1, 192.168.1.22, 192.168.1.2'}
>>> e
'192.168.1'
>>> match = re.search(e, d['server'])
>>> if match:
... print match.group()
...
192.168.1
If you’re only trying to match an IPv4 address, you can use the regex 192\.168\.1\.\d+
.
>>> import re
>>> text = '192.168.1.2, 192.168.11.9, 192.168.1.255, 10.14.1.1'
>>> regex = '192\.168\.1\.\d+'
>>> re.search(regex, text).group()
'192.168.1.2'
>>> re.findall(regex, text)
['192.168.1.2', '192.168.1.255']
In a regular expression pattern, a .
without a \
(well, a \\
for Python) in front of it is a special character which matches any one character. Are you looking for IP addresses that start with your pattern? For that use 192\\.168\\.1\\.\d+
or some variant. Alternatively, if you can get each of those IPs into a string by itself then you can use:
if ip.startswith(e):
# etc.
精彩评论