0

This is what i have now :

import re

x = "From: Joyce IP: 192.111.1.1 Source: 192.168.1.1"    
x = x.replace(' ', '')
m = re.findall('(?<=:)\S+', x)
print m 

And I want to have a output like this to make this $ script.py > result.txt:

Joyce 192.111.1.1 192.168.1.1

3 Answers 3

2

Instead of finding the matches of the text you want as the result, it may be easier to replace the stuff you don't want:

>>> import re
>>> x = "From: Joyce IP: 192.111.1.1 Source: 192.168.1.1"
>>> re.sub(r'\w+:\s', '', x)
'Joyce 192.111.1.1 192.168.1.1'

However, if you prefer to use re.findall() here is one option that is similar to your current approach:

>>> ' '.join(re.findall(r'(?<=:\s)\S+', x))
'Joyce 192.111.1.1 192.168.1.1'

You need the \s in the negative lookbehind because there is a space after each of the colons in your input string.

Sign up to request clarification or add additional context in comments.

2 Comments

that is exactly what i'm talking about this is easy to someone else damn, sorry to ask F.J why did you use sub instead of search of findall ?
@PythonNewbie I added a version that uses findall, but I generally find it easier to understand expressions that don't use lookbehind or lookahead, and using sub makes that possible.
0

a slight change to your code (don't remove the spaces, and include them in the look behind) works perfectly:

import re

x = "From: Joyce IP: 192.111.1.1 Source: 192.168.1.1"    
m = re.findall('(?<=:\s)\S+', x)
print " ".join(m) 

Comments

0
import re

x = "From: Joyce IP: 192.111.1.1 Source: 192.168.1.1"    

reg = r"\d{1,3}(?:[.]\d+){3}"

m = re.findall(reg, x)

for i in m:
  print(i)

Result : 192.111.1.1 192.168.1.1

1 Comment

A cleaner way of addressing the problem, for those who are looking for answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.