用于字符串解析的Python正则表达式

问题描述 投票:0回答:1

我正在尝试为python学习正则表达式,并尝试在字符串中获取令牌和会话值。我在下面看到,但是从这里获取令牌和会话值还有更好的方法吗?这是我的代码也是字符串:

    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"
regex python-3.x
1个回答
0
投票

您可以使用非常简单的正则表达式来获取它:

a=re.findall("[a-zA-Z0-9-]+", b)
print(a[1]) # Outputs d9706bc7-c599-4c99-b55e-bc49cba4bc0d

甚至更短,将给您相同的结果:

a=re.findall("[\w-]+", b)
print(a[1]) # Outputs d9706bc7-c599-4c99-b55e-bc49cba4bc0d
© www.soinside.com 2019 - 2024. All rights reserved.