I'm trying to learn regex for python and try to get token and session values in the string. I get as in the below but is there a better way from here to get token and session values? here is my code also string:
a ={}
import re
b ="token: d9706bc7-c599-4c99-b55e-bc49cba4bc0d\nsession:NjA5MWE2MGQtMTgxNS00NWY5LTkwYWQtM2Q0MWE3OTFlNTY0\n"
a=re.findall("([A-Za-z]+[\d@]+[\w@]*|[\d@]+[A-Za-z]+[\w@])",b)
print(a[5]) #this is for session value "NjA5MWE2MGQtMTgxNS00NWY5LTkwYWQtM2Q0MWE3OTFlNTY0"
print ([a[0:5]]) #this is for getting token as array d9706bc7 c599 4c99 b55e bc49cba4bc0d
How can I get the token value with - as in the below:
"d9706bc7-c599-4c99-b55e-bc49cba4bc0d"
1 Answer 1
You can use a very simple regexp to get it:
a=re.findall("[a-zA-Z0-9-]+", b)
print(a[1]) # Outputs d9706bc7-c599-4c99-b55e-bc49cba4bc0d
Even shorter, will give you same result:
a=re.findall("[\w-]+", b)
print(a[1]) # Outputs d9706bc7-c599-4c99-b55e-bc49cba4bc0d
answered May 1, 2020 at 3:16
dmitryro
3,5142 gold badges23 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
laura
thank you :) @dmitryro so I have to write a new regex to take session value? is there any shorter way to get token and session values ?
lang-py