user2205916
user2205916

Reputation: 3456

Hive regular expressions for IP addresses

How do I modify the following code:

SELECT regexp_extract('156.154.161.94', '[A-Za-z0-9-]+\.[A-Za-z0-9-]+\.$', 0) AS ip;
161.94

To return the first 2 or 3 octets of the IP address? In other words: 156.154 or 156.154.161?

Upvotes: 1

Views: 877

Answers (2)

leftjoin
leftjoin

Reputation: 38335

Shorter regexp:

SELECT regexp_extract('156.154.161.94', '\\d+\\.\\d+', 0) AS ip; --first 2 quibbles.

Note that correct regexp special characters escaping in Hive is two slashes: \\. not one \., not \d.

Upvotes: 0

nobody
nobody

Reputation: 11090

First two

SELECT regexp_extract('156.154.161.94', '[0-9]+\.[0-9]+', 0) AS ip;

First three

SELECT regexp_extract('156.154.161.94', '[0-9]+\.[0-9]+\.[0-9]+', 0) AS ip;

Upvotes: 2

Related Questions