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

标签 python regex

我制作了此模式来获取博客文章的 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/

相关文章:

python - Numpy 列出第二轴

正则表达式匹配后面没有一个字符的单个字符

javascript - RegExp 中的别名 ls ="ls --color"?

c# - 如何在C#中模拟元组和集合?

python - 在OpenCv中从图像提取墙

java - Java 正则表达式的 StackOverFlow 错误

c# - 作为匹配的一部分返回常量值的正则表达式

php - 正则表达式捕获额外的字符

python - 使用python在命令提示符下更改当前工作目录

python - 获取不规则形状的中心