Python. How To Print A Certain Part Of A Line After It Had Been "re.searched" From A File
Solution 1:
You will need to modify your regex slightly to separate the trailing characters in the IP and the spaces that separate it from VSP. Adding a capture group will let you select the portion with just the IP address. The updated regex looks like this:
'(\d+\.226\.\S+)\s+' + VSP
\S
(uppercase S) matches any non-whitespace, while \s
(lowercase s) matches all whitespace. I replaced the first \w
with the more specific \d
(digits), and .
(any character at all) with \.
(actual period). The second \w
is now \S
, but you could use \d+\.\d+
if you wanted to be more specific.
Using the first capture group will give you the IP address:
print(b.group(1))
If you are looking for a single IP address once, not compiling your regex is fine. Also, reading in a small file in its entirety is OK as long as the file is small. If either is not the case, I would recommend compiling the regex and going through the file line by line. That will allow you to discard most lines much faster than using a regex would do.
Solution 2:
I see you already have an answer.You can also try this regex if you were to separate the two groups by the whitespace:
import re
a = re.compile(r'(.+?)\s+(.+)') # edit: added ? to avoid# greedy behaviour of first .+# otherwise multiple spaces after the# address will be caught into# b.group(1), as per @Mad comment
b=re.search(a, '10.226.27.60 1020')
print (b.group(0))
print (b.group(1))
print (b.group(2))
or customize the first group regexp to your needs.
Edit: This was not meant to be a proper answer but more of a comment wich I didn't think was readable as such; I am trying only to show group separation using regex, wich seems OP didn't know about or didn't use. That is why I am not matching .226. because OP can do that. I also removed the file read part, which isn't needed for demonstration. Please read @Mad answer because its quite complete and in fact also shows how to use groups.
Post a Comment for "Python. How To Print A Certain Part Of A Line After It Had Been "re.searched" From A File"