-1

I have simple script for combining through ip addresses. I'd like to regex the ip from the following output

Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-11 15:04 EST
Nmap scan report for host.com (127.0.0.1)
Host is up (0.14s latency).

I tried using this tool: https://pythex.org/. I was able to get a match with the following pattern

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

however this code returns 0 matches

regex = re.match("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})",output)
print(regex)

the expected output should be 127.0.0.1. Any help with this would be greatly appreciated.

Evan Gertis
  • 1,796
  • 2
  • 25
  • 59
  • Try like this r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$" Replace regular expression with this one – Sachin Rajput Dec 12 '20 at 03:45
  • Does this answer your question? [Python regular expression re.match, why this code does not work?](https://stackoverflow.com/questions/14933771/python-regular-expression-re-match-why-this-code-does-not-work) – Nick Dec 12 '20 at 04:07

3 Answers3

1

re.match matches a pattern at the beginning of the given string. It looks like what you want is re.findall or re.search:

output = '''
Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-11 15:04 EST
Nmap scan report for host.com (127.0.0.1)
Host is up (0.14s latency).'''

regex = re.findall("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", output)

print(regex) # ['127.0.0.1']
ssp
  • 1,666
  • 11
  • 15
0

You should use re.search

>>> import re
>>> text = 'Nmap scan report for host.com (127.0.0.1)'
>>> re.search(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", text).group()
'127.0.0.1'
Akash Ranjan
  • 922
  • 12
  • 24
0

with re.match you can use it as follows:

output = 'Your output'
ip = re.match(r'\(([\d\.]*)\)').groups()[0]

Explaination : re.match will return a class which is surrounded by brackets and have "." and digits only. The groups() will then return all matching groups. the string at index[0] will be the match for it.

shekhar chander
  • 600
  • 8
  • 14