I have already tried with the following code, but I get an empty list []
On the contrary, when I run you code, I get the following:
import re
str_2 = '''IP_Add1 192.168.10.1 LAN 10
IP_Add1 192.168.10.1 LAN 20
IP_Add1 192.168.20.1 LAN 30
IP_Add1 192.168.30.1 LAN 40
'''
print(re.findall(r"\w+ [\d]{3}.[\d]{3}.[\d]{2}.[\d]{1}", str_2))
#['IP_Add1 192.168.10.1', 'IP_Add1 192.168.10.1', 'IP_Add1 192.168.20.1', 'IP_Add1 192.168.30.1']
This is because re.findall
will:
Return a list of all non-overlapping matches in the string.
But based on your wording, what you actually want to do is better accomplished using re.sub
:
res = re.sub(r"(?<=IP_Add\d )\d{3}\.\d{3}\.(?=\d{2}\.\d{1})", "", str_2)
print(res)
#IP_Add1 10.1 LAN 10
#IP_Add1 10.1 LAN 20
#IP_Add1 20.1 LAN 30
#IP_Add1 30.1 LAN 40
If you wanted your results in a list, you can call the splitlines()
method:
print(res.splitlines())
#['IP_Add1 10.1 LAN 10',
# 'IP_Add1 10.1 LAN 20',
# 'IP_Add1 20.1 LAN 30',
# 'IP_Add1 30.1 LAN 40']
The regular expression pattern used in sub
is the following:
(?<=IP_Add\d )
: Look-behind for the literal string "IP_Add"
followed by exactly one digit and one space
\d{3}\.\d{3}\.
: Three digits followed by a literal period, followed by another 3 digits and a literal period.
(?=\d{2}\.\d{1})
: Look-ahead for two digits, a period, and then one digit.