简体   繁体   中英

How to grab first ip address from a string

I am trying to grab an ip address from a string and facing an issue.please help.
inet addr:11.11.11.11 Bcast:11.11.11.111 Mask:111.111.11.1 .
This is the string I have and I need ip address next to addr:

I have tried the following code and failed to do in python:

ip = re.findall(r'(?:\\d{1,3}\\.)+(?:\\d{1,3})', line) and get index 0 item.

Result : This is actually giving me nothing in return

Your REGEX could be more specific, I think you could use something like :

addr:(?<ip>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})

In python:

match = re.match(r'addr:(?<ip>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})', line)

You can then access the ip group by calling match.group('ip') .

I noted that your regex will match invalid IPv4 addresses.

import re

string = 'inet addr:300.11.11.11  Bcast:11.11.11.111  Mask:111.111.11.1'

# your pattern 
ip_address_pattern = re.compile(r'(?:\d{1,3}\.)+(?:\d{1,3})')
find_ip_address = re.findall(ip_address_pattern, string)
if find_ip_address:
   print (find_ip_address)
   # outputs
   ['300.11.11.11', '11.11.11.111', '111.111.11.1']

I have used this IPv4_format in the past to extract valid IPv4 addresses.

import re

string = 'inet addr:11.11.11.11  Bcast:11.11.11.111  Mask:111.111.11.1'

# Valid IPv4 address format
ip_address_pattern = re.compile(r'\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')
find_ip_address = re.findall(ip_address_pattern, string)
if find_ip_address:
  print (find_ip_address)
  # outputs
  ['11.11.11.11', '11.11.11.111', '111.111.11.1']
import re

line = "inet addr:11.11.11.11  Bcast:11.11.11.111  Mask:111.111.11.1"

pattern = r"[\d]{2}[.][\d]{2}[.][\d]{2}[.][\d]{2}[\D]"

re.findall(pattern, line)

['11.11.11.11 ']

re.findall(pattern, line)[0].strip()

'11.11.11.11'

if you have more than one element in the list just run a list-comp using .strip()

[i.strip() for i in re.findall(pattern, line)]

['11.11.11.11']

re.match() is not going to work because it will try to match your pattern starting at the beginning of the string (granted that your pattern does not include the " " portion. ”部分。
re.search() works but it misses recurring elements and only returns the first encounter of the pattern upon a successful match, in addition you'll have to use filter to extract the element.

finally, the key to solving this problem lies in the last character of your target, xx.xx.xx.xx[\\D] . The [\\D] directive ensures that the pattern looks for a no-integer at index 12, [\\s] works equally well and it matches a space.

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