You are here:  Home > Useful > Regular Expressions Last updated 30 Dec 2012   

Regular Expressions

Regular Expressions are used to make specific matches in arbitrary text. If you wanted to match an IP Address in a sequence of text all you have to do is define a regular expression for the format of the IP Address and then set it loose on the text. Since an IP Address (in IPv4) is a sequence of four octets sepearted by dots, a suitable regular expression is:

  (\d+\.){3}\d+

where \d is a numeric character (0 to 9), \d+ is 1 or more numeric characters, \d+\. is one or more numeric characters followed by a dot (the \. simply means that the character has the meaning of a dot rather than its special meaning of any character in the text). The (\d+\.){3} means that the numeric string followed by a dot needs to occur three times. The final \d+ means that one or more numeric characters need to follow the final dot of the previous string.

If the IP address can be isolated from a sequence of text, the regular expression can be made stricter by having the text match start at the first charcater in the string and end at the last character. This is done with the ^ and $ characters:

  ^(\d+\.){3}\d+$

Finally to ensure that the IP Address is actually in the IP format, the matched string could be checked to ensure that each octet only consists of at least one and no more than three numeric characters. If you want to know more, check out:

  RegExp Studio (Be careful. See the note below)

This site has a useful introduction to regular expressions at:

  RegExp intro (Be careful. See the note below)

and is easier to use than other sources. To test out regular expressions you can make use of the TestRExp project. However, if you don't use Delphi, a copy of the program compiled from the project files can be downloaded from TestRExp (we use this ourselves without problems. [459Kb, MD5 checksum: 34522048D14E1C2B62267A79ADA78918]). Try it with ^(\d+\.){3}\d+$ as the regular expression and 192.168.0.1 as the input string.

Note: The safety of arbitrary links on a web page cannot be guaranteed. Ensure that the Internet Zone of your browser has Active Scripting (i.e. Javascript) disabled. This prevents a good proportion of potential security breaches.
Why does Note above have a link? If the page grows in future, clicking that link will scroll the page down to the word Note which is an anchor tag with a Name attribute.

AllIncontext Limited is registered in England, No 04624520. Registered office address: 12-14 High Street, Petersfield, Hampshire, GU32 3JG.

Valid XHTML 1.0 Strict   Valid CSS!