1

I am a beginner in Python and struggling for a simple code. I have a string like :

ERROR_CODE=0,ERROR_MSG=null,SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2|||33a3b23d-2143

I want to get the SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2 from the string using re.search().

My Code:

line=ERROR_CODE=0,ERROR_MSG=null,SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2|||33a3b23d-2143
sessionId=re.search(r'SESSION_ID=*|',line)
            if sessionId:
                print sessionId     
            else:
                print "Session id not found"

On executing this, i am getting the result as ,

<_sre.SRE_Match object at 0x0000000001EB8D98>

But i need the result as SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2. Where i am going wrong?Thanks in advance

Marcin
  • 215,873
  • 14
  • 235
  • 294
Deepika Soren
  • 181
  • 2
  • 3
  • 12

2 Answers2

3

Your problem is 'SESSION_ID=|'. Character '|' should be escaped, and instead of * should be '.'.

sessionId=re.search(r'SESSION_ID=.*\|',line)

if sessionId:
    print(sessionId.group())     
else:
    print("Session id not found")

Result is:

SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2|||

Probably there are better ways of doing your search for this, but I just applied the simplest changes to your regexp.

Better way would be e.g.

sessionId=re.search(r'(SESSION_ID=[\w-]+)\|',line)

if sessionId:
    print(sessionId.group(1))     
else:
    print("Session id not found")

This gives:

SESSION_ID=2a50250f-4a2e-4bf9-b1a7-7a8030333de2
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • I used the above but unfortunately its not working for me.I am using Python 2.7 and i am getting "Session id not found" – Deepika Soren Dec 03 '14 at 08:54
  • I just tested in 2.7.7. and seems to work. Do you have the same line as in your question? Maybe it does not work for other line? – Marcin Dec 03 '14 at 10:17
0

search captures in group:
replace :

print sessionId 

to:

print sessionId.group()     

demo:

>>> a = "hello how are you"
>>> k= re.search('[a-z]+',a)
>>> k
<_sre.SRE_Match object at 0x7f9c456fe030>
>>> k.group()
'hello'
Hackaholic
  • 19,069
  • 5
  • 54
  • 72