我有一个这样的字符串:"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]
所有以“#”开头的术语,而不是第一个术语。在
像Python这样的好编程语言不需要正则表达式:
你可以用
输出:
^{pr2}$但是有一个问题。如果搜索类似
'blahblahblah #Syrup #nshit #thebluntislit beg#end'
的字符串,输出将是['#Syrup', '#nshit', '#thebluntislit', '#end']
。在这个问题可以通过使用正向回溯来解决:
(在这里不可能使用
\b
(单词边界),因为#
不在\w
符号[0-9a-zA-Z_]
之间,这可能构成正在搜索的边界的单词)。在似乎
re.findall()
将执行您想要的操作。在相关问题 更多 >
编程相关推荐