I am working with python 2.7 on Linux. I prepare a regular expression which should detect that a string is in the following format:
tcp:IP_ADDR:PORT-IP_ADDR:PORT or udp:IP_ADDR:PORT-IP_ADDR:PORT
I have the following short script for regular expression:
import re
my_str="tcp:192.168.0.1:111-10.0.0.2:22"
regx_ip = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
regx_hostfwd = r'["tcp" | "udp"]?:%s?:\d+-%s?:\d+' % (regx_ip, regx_ip)
if not re.match(regx_hostfwd, my_str):
print("fail")
else:
print("success!")
When I run it I get: "fail" However, when I change it to use re.search, thus: ...
my_str="tcp:192.168.0.1:111-10.0.0.2:22"
regx_ip = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
regx_hostfwd = r'["tcp" | "udp"]?:%s?:\d+-%s?:\d+' % (regx_ip, regx_ip)
if not re.search(regx_hostfwd, my_str):
print("fail")
else:
print("success!")
...
and run it, I get "success!". I don't understand what is the reason for this. According to my understanding, match looks from the start of the input while search looks anywhere in the input. According to my understanding, in this case it should return success in both cases. What should I do so it will return success also when using "match"?
Regards, Kevin