Detecting IPs in a string

So, I ahve this function to detect if a IP is in a string:



function HasIP( String )
   if !String then return end
   local String = string.lower(String)

   if string.match( String, string.rep( "%d%d?%d?%.", 3 ) .. "%d%d?%d?" ) then return true end 
end


The problem is that this only detects IPs formatted like xxx.xxx.xxx.xxx but not xxx.xxx.x.x or xxx.xxx.xx.xx(.) If I’m wrong please feel free to tell me so and explain why.



local IPs = {
	"129.420.90.20",
	"1.2.3.4",
	"420.420.420.420",
	"20.40.60.80",
	"240.420.10.20"
}

for _, ip in pairs(IPs) do
	print(string.match(ip, string.rep("%d%d?%d?%.", 3) .. "%d%d?%d?"))
end


prints out



129.420.90.20
1.2.3.4
420.420.420.420
20.40.60.80
240.420.10.20


As for allowing the use of a period at the end (even though I never see IP Addresses with a period at the end) just add %.? to the end of the pattern. Also, why are you using string.lower on a string before you try to match the IP Address? The numbers and periods aren’t going to change case when you use that function on them anyway.

You should read this http://lua-users.org/wiki/PatternsTutorial

[lua]local tests = {
“1.2.3.4”, “11.22.33.44”, “111.222.255.0”,
“1.22.333.4”, “1.22.333.4444”, “44.222.1.33”,
“in.va.l.id”, “1111.44.33”, “333.333.333.333”,
“5.5.5.5”
}

function findip(str)
return string.match(str, “[12]?%d%d?%.[12]?%d%d?%.[12]?%d%d?%.[12]?%d%d?”)
end

for k, v in pairs(tests) do
print(findip(v))
end[/lua]

prints out


1.2.3.4
11.22.33.44
111.222.255.0
nil
nil
44.222.1.33
nil
nil
nil
5.5.5.5

[12] could capture “1” or “2” because 3 digit IP’s can only start with 1 or 2
%d captures only numbers
%d? could capture a number if it’s there
%. captures the character “.”

I’m not sure why you would want to capture a “.” at the end because no IPs have a fourth dot

It not only starts with 1 or 2 but doesn’t go above 255.

I put the period there to end the sentence trying to put in it parentheses was my attempt at separating it. As for it not being able to go above 255, I’ll have to figure something out for that.

[editline]14th May 2016[/editline]

I use string.lower because I’m finding the IP in a string for example:



local test = "Player1's IP is 192.168.1.1"

function HasIP( String )
	if !String then return end
	local String = string.lower( String )

	if string.match( String, string.rep( "%d%d?%d?%.", 3 ) .. "%d%d?%d?" ) then return true end
end

print( HasIP( test ) )


But changing the case will have no effect on those digits, nor will it stop the pattern from finding them.

Only if you were trying to find IPv6 ips would it make sense.