Skip to content Skip to sidebar Skip to footer

Printing Result Of Re.search In Python

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 wa

Solution 1:

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

Solution 2:

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'

Post a Comment for "Printing Result Of Re.search In Python"