简体   繁体   中英

Regex to extract last two octets of IP address (3rd and 4th Octet) in Google Sheets

I need help to extract last two octets of IP address (3rd and 4th Octet) by using regular expresssion.

This regex works to extract first two octet (1st and 2nd Octet) :

(1?\d\d?|2[0-4]\d|25[0-5])

You can try it here https://rubular.com/r/ynDa71Zd1M2f24

But I dont know how to extract 3rd and 4th octet. Anybody can help me with?

  • Input: 192.168.1.1 Output: 192.168.0.0/16
  • Input: 192.168.2.1 Output: 192.168.0.0/16
  • Input: 10.10.1.1 Output: 10.10.0.0/16

Thank you,

Solution

You can use something like this:

(?P<first>\d{2,3})\.(?P<second>\d{1,3})\.(?P<third>\d{1,3})\.(?P<fourth>\d{1,3})

Or if you don't have named capture group support just use:

(\d{2,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})

This will split your strings into four different groups, each containing one octet of the ip.

Example

import re

pattern = r"(?P<first>\d{2,3})\.(?P<second>\d{1,3})\.(?P<third>\d{1,3})\.(?P<fourth>\d{1,3})\n?"
matcher = re.compile(pattern)

ips = """
192.168.1.1
192.168.1.2
"""

result = matcher.findall(ips) # [('192', '168', '1', '1'), ('192', '168', '1', '2')]

You could use for example a pattern to match an ip like format and use a capturing group for the first 2 parts including the dot.

In the replacement use the capturing group value $1 followed by 0.0/16

=REGEXREPLACE(A2,"^(\d{1,3}\.\d{1,3}\.)\d{1,3}\.\d{1,3}$","$10.0/16")

See a regex demo

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM