Python Forum

Full Version: Extract Specific Pattern
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,

How do I extract specific pattern in below code. As I have tried to get expected output through regex and use Python Dictionary in order to fetch it through values but unable to get it.


#!/usr/bin/python
import re


line = '''CLIENT LIST
Updated,Wed Sep 19 10:22:48 2018
Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since
dell,110.23.15.12:50731,14298,15058,Wed Sep 19 09:59:23 2018
sony,110.23.15.12:48050,93394,98996,Wed Sep 19 10:21:44 2018
ROUTING TABLE
Virtual Address,Common Name,Real Address,Last Ref
192.168.250.114,dell,110.23.15.12:48050,Wed Sep 19 10:22:46 2018
192.168.250.50,sony,110.23.15.12:50731,Wed Sep 19 09:59:25 2018
GLOBAL STATS
Max bcast/mcast queue length,0
END'''

dict = re.findall(r'^\d(.*?,\s*(.*?),)', line, re.M)

if dict:
 print "Users Connected", dict
else:
 print "Nothing found!!"
Output:
Output:
Users Connected: [('92.168.250.114,dell,', 'dell'), ('92.168.250.50,sony,', 'sony')]
Expected Output:
Output:
Users Connected: dell, sony and so on...
Regards,
rlinux57
That looks more like "desired output" than "expected output" - the string "Users Connected" never appears in your code. Also, there are no dictionaries here, why do you think there are?

If I wanted to produce your desired result from the code you've provided, I'd simplify the regex, since it looks like you don't need the IP address (from what you've described) and then I would use the list of strings from findall to generate the desired string. I'm not sure what your programming background is, but that would probably help us to tailor a specific answer to you.
Hi,

I have edited and print the "Users Connected" to dispel your confusion. I just want to get names through regex. But i am bit weak in regex to extract desired output. When i used python dictionary like dict[0][1] It shows only single value. I am not sure how to give a range so that it shows all the values stored in dict variable.
(Sep-25-2018, 05:12 AM)rlinux57 Wrote: [ -> ]Hi,

I have edited and print the "Users Connected" to dispel your confusion. I just want to get names through regex. But i am bit weak in regex to extract desired output. When i used python dictionary like dict[0][1] It shows only single value. I am not sure how to give a range so that it shows all the values stored in dict variable.

Learn non-capturing group

Output:
In [44]: re.findall(r'(?m)^(?:[\d\.]+,)(\w+)', line) Out[44]: ['dell', 'sony']
PS Never use names of Python built-in objects as variable names
Hi Volcano63,

Thank you for your answer, I used: ^\d[0-9]+(?:\.[0-9]+){3},(\w+)

Regards,
rlinux57