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+'
  • 3
    Related: [Why does my regular expression work in X but not in Y?](https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y) - in particular note that the `+` quantifier is part of the *extended* regular expression syntax and `\d` is from the perl (PCRE) extension set – steeldriver Jan 10 '21 at 18:29
  • Note that when you figure out how to get your `grep` to understand `\d` as "a digit", you still would match e.g. `000.0002222.020202020.020.0.0.0.0.0` with that expression. – Kusalananda Jan 10 '21 at 18:53
  • Thanks for answering, didn't know there were so many types. this is really confusing. – ajmandourah Jan 11 '21 at 09:35

2 Answers2

1

Use grep -P:

-P, --perl-regexp         PATTERNS are Perl regular expressions
GAD3R
  • 63,407
  • 31
  • 131
  • 192
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
Eduardo Trápani
  • 12,032
  • 1
  • 18
  • 35