1

I am learning regular expressions and as aa practice I tried grep'ing an ip address but it fails to get any results. I tried it out on VSCode and it works. Anyone can enligheten me where did I go wrong?

echo 192.168.1.1 | grep -e '\d+\.\d+\.\d+\.\d+'

2 Answers2

1

Use grep -P:

-P, --perl-regexp         PATTERNS are Perl regular expressions
GAD3R
  • 66,769
0

Note that regular expressions are not really meant for parsing things like IPv4 addresses. You can try to do it, to a certain level of accuracy:

Your expression \d+\.\d+\.\d+\.\d+ would match any four groups of digits separated by a dot, if \d matched a digit on its own.

Keep in mind that regular expressions have many flavors and results may vary, depending on the engine being used. When you use grep -P as suggested in another answer, you change the parsing engine.

In Matching IPv4 Addresses - Regular Expressions Cookbook by O'Reilly you have some examples.

This checks for (just) an IP address, not many checks though, 299.299.111.1 would pass:

^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$

The other examples in the page try to narrow down the detection to get a valid IP address, see what they propose for accurate extraction from longer text and you'll know why IPv4 addresses are not a good playground for regular expressions:

\b(?:(?: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]?)\b