As your regexp gets complicated, it can get difficult to debug if you run into issues. Building your regexp step by step from scratch and testing against input strings will go a long way in correcting the problem. To aid in such a process, you could use various online tools.
rubular is an online Ruby regular expression editor (based on Ruby 2.5.7) to visually test your regexp. You need to add your regexp, input string and optional modifiers. Matching portions will be highlighted.
The below image is a screenshot from this link — rubular:
The below image is a screenshot from this link — debuggex:
The below image is a screenshot from this link — regexcrossword: tutorial puzzle 5
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 CommonRegexRuby. See also Awesome Regex: Collections.
>> require 'commonregex' => true >> data = 'hello 255.21.255.22 okay 23/04/96' # match all available patterns >> parsed = CommonRegex.new(data) >> parsed.get_ipv4 => ["255.21.255.22"] >> parsed.get_dates => ["23/04/96"] # or, use specific method directly on CommonRegex >> CommonRegex.get_ipv4(data) => ["255.21.255.22"] >> 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 = '126.96.36.199.2 255.21.255.22 5188.8.131.52' # 184.108.40.206 gets matched from 220.127.116.11.2 >> CommonRegex.get_ipv4(new_data) => ["18.104.22.168", "255.21.255.22"]