gpt4 book ai didi

python - 使用 finditer 后如何从正则表达式匹配对象中获取匹配的单词

转载 作者:行者123 更新时间:2023-12-01 00:51:43 26 4
gpt4 key购买 nike

我制作了此模式来获取博客文章的 url 链接(可以在我的网站 url 中用连字符或下划线等分隔,以将其与数据库匹配并显示相应的帖子)。每当我将匹配项附加到列表中时,它们都是重新匹配对象。如何获取匹配的单词?

我尝试过使用搜索和匹配,但它们不会返回单独的单词。

import re
pattern = r"[a-zA-Z0-9]+[^-]+"
matches = re.finditer(pattern, "this-is-a-sample-post")
matches_lst = [i for i in matches]

假设我有字符串“this-is-a-sample-post”,我想得到“this is a example post”。

我想要一个匹配单词的列表,以便我可以使用“”.join() 方法并将字符串与我的数据库进行匹配。

最佳答案

import re
pattern = r"[a-zA-Z0-9]+[^-]+"
string = "this-is-a-sample-post"
matches = re.finditer(pattern, string)
matches_lst = [i.group(0) for i in matches]
print("Made with finditer:")
print(matches_lst)
print("Made with findall")
matches_lst = re.findall(pattern, string)
print(matches_lst)
print("Made with split")
print(string.split("-"))
print("Made with replace and split")
print(string.replace("-"," ").split())

输出:>>>

Made with finditer:
['this', 'is', 'sample', 'post']
Made with findall
['this', 'is', 'sample', 'post']
Made with split
['this', 'is', 'a', 'sample', 'post']
Made with replace and split
['this', 'is', 'a', 'sample', 'post']
>>>

关于python - 使用 finditer 后如何从正则表达式匹配对象中获取匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56520050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com