Using RegEx to validate an ip-address

moster67

Expert
Licensed User
Longtime User
Anyone who knows which pattern to use to validate an ip-address?

such as:

192.168.1.83

Thanks.
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log(IsValidIp("192.168.1.83"))
   Log(IsValidIp("192.168.2221.83"))
End Sub

Sub IsValidIp(ip As String) As Boolean
   Dim m As Matcher
   m = Regex.Matcher("^(\d+)\.(\d+)\.(\d+)\.(\d+)$", ip)
   If m.Find = False Then Return False
   For i = 1 To 4
      If m.Group(i) > 255 OR m.Group(i) < 0 Then Return False
   Next
   Return True
End Sub
As you see I combine RegEx with some code. It is much easier to validate it this way.
 
Upvote 0

moster67

Expert
Licensed User
Longtime User
Thanks once again Erel for your incredible support. :sign0188:

I tested it with a few scenarios (wrong and strange user-inputs) and it works very nice.
 
Upvote 0

TomasRiker

New Member
Hi!

Actually you don't have to check for "< 0", because there can't be a minus sign. \d only matches the digits 0 through 9.

Also, it is possible to do the "< 256" check in the regex.
It gets a bit more complex then, but well possible:

B4X:
(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|2[0-4]\d|25[0-5])

This is from my article about IP address matching with regular expressions.
( regex-for.com/ip-addresses/ )
 
Upvote 0
Top