KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: How to Detect an IP Address Using Match regex
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: December 17, 2010

The Match regex command can be used to easily test if a string is an IP address.

Here is a simple example of a method to test if the passed text value looks like an IP address:

C_TEXT($1;$testText_t)
C_BOOLEAN($0;$isIPAddress_f)

C_TEXT($IPAddressPattern_t)

$testText_t:=$1

$IPAddressPattern_t:="[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"

$isIPAddress_f:=Match regex($IPAddressPattern_t;$testText_t)

$0:=$isIPAddress_f


In fact this example only verifies if the passed text has the structure of an IP address. That is, the pattern checks for 4 groups made up of from 1 to 3 numbers, separated by 3 dots. It would not invalidate 999.999.999.999 for example (but this is not a valid IP address).

If you would like to validate that the value really could be used as an IP address, use a more complex pattern like this one:

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