删除uuid4字符串模式

2024-06-16 08:53:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的字符串示例

1# 00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin

2# 00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin

我试图删除uuid4生成的字符串以及python中uuid4字符串模式右侧的任何文本。在

在这两个例子中,输出都应该是00000 Gin

我在这里查过了What is the correct regex for matching values generated by uuid.uuid4().hex?。但还是无济于事。在


Tags: the字符串文本示例is模式what例子
1条回答
网友
1楼 · 发布于 2024-06-16 08:53:50

您可以使用:

import re

strings = ["00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin",
"00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin"]

rx = re.compile(r'^[^-]+')
# match the start and anything not - greedily

new_strings = [match.group(0)
                for string in strings
                for match in [rx.search(string)]
                if match]
print(new_strings)
# ['00000 Gin', '00000 Gin']


a demo on ideone.com
如果字符串是所需的格式,则可以使用以下表达式: ^{pr2}$

regex101.com(注意修饰符!)上查看这个演示。在

相关问题 更多 >