如何获取以“#”开头的所有术语?

2024-09-29 21:57:47 发布

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

我有一个这样的字符串:"sometext #Syrup #nshit #thebluntislit"

我想得到一个以“#”开头的所有术语的列表

我使用了以下代码:

import re
line = "blahblahblah #Syrup #nshit #thebluntislit"
ht = re.search(r'#\w*', line)
ht = ht.group(0)
print ht

我得到以下结论:

^{pr2}$

我想知道是否有一种方法可以代替我得到一份清单,比如:

[#Syrup,#nshit,#thebluntislit]

所有以“#”开头的术语,而不是第一个术语。在


Tags: 字符串代码importre列表searchlinegroup
3条回答

像Python这样的好编程语言不需要正则表达式:

  hashed = [ word for word in line.split() if word.startswith("#") ]

你可以用

compiled = re.compile(r'#\w*')
compiled.findall(line)

输出:

^{pr2}$

但是有一个问题。如果搜索类似'blahblahblah #Syrup #nshit #thebluntislit beg#end'的字符串,输出将是['#Syrup', '#nshit', '#thebluntislit', '#end']。在

这个问题可以通过使用正向回溯来解决:

compiled = re.compile(r'(?<=\s)#\w*')

(在这里不可能使用\b(单词边界),因为#不在 \w符号[0-9a-zA-Z_]之间,这可能构成正在搜索的边界的单词)。在

似乎re.findall()将执行您想要的操作。在

matches = re.findall(r'#\w*', line)

相关问题 更多 >

    热门问题