Interlude: Common tasks

Tasks like matching phone numbers, ip addresses, dates, etc are so common that you can often find them collected as a library. This chapter shows some examples for the CommonRegexRuby gem. See also Awesome Regex: Collections.


You can either install the commonregex gem or go through commonregex.rb and choose the regular expression you need. See also CommonRegexRuby: README for details and examples of available patterns. Here's an example for matching ip addresses:

>> require 'commonregex'
=> true

>> data = 'hello okay 23/04/96'

# match all available patterns
>> parsed =
>> parsed.get_ipv4
=> [""]
>> parsed.get_dates
=> ["23/04/96"]

# or, use a specific method directly on CommonRegex
>> CommonRegex.get_ipv4(data)
=> [""]
>> CommonRegex.get_dates(data)
=> ["23/04/96"]

Make sure to test these patterns for your use case. For example, the below data has a valid IPv4 address followed by another number separated by a dot character. If such cases should be ignored, then you'll have to create your own version of the pattern or change the input accordingly.

>> new_data = ' 567.12.2.1'

# gets matched from
>> CommonRegex.get_ipv4(new_data)
=> ["", ""]


Some patterns are quite complex and not easy to build and validate from scratch. Libraries like CommonRegexRuby are helpful to reduce your time and effort needed for commonly known tasks. However, you do need to test the solution for your use case. See also stackoverflow: validating email addresses.