Reputation: 181
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
Upvotes: 1
Views: 8042
Reputation: 238597
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
Upvotes: 3
Reputation: 19753
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'
Upvotes: 0