【发布时间】:2012-09-27 05:10:39
【问题描述】:
我正在尝试在 Python 中创建一个匹配 #hashtags 的正则表达式。我对主题标签的定义是:
- 这是一个以
#开头的作品 - 可以包含除
[ ,\.]以外的所有字符 - 可以在文本中的任何位置
所以在本文中
#This string cont#ains #four, and #only four #hashtags.
这里的哈希值是This、four、only 和hashtags。
我遇到的问题是对行首的可选检查。
-
[ \.,]+不会这样做,因为它与可选的开头不匹配。 -
[ \.,]?不会这样做,因为它匹配的太多。
带 + 的示例
In []: re.findall('[ \.,]+#([^ \.,]+)', '#This string cont#ains #four, and #only four #hashtags.')
Out[]: ['four', 'only', 'hashtags']
示例 ?
In []: re.findall('[ \.,]?#([^ \.,]+)', '#This string cont#ains #four, and #only four #hashtags.')
Out[]: ['This', 'ains', 'four', 'only', 'hashtags']
可选如何匹配行首?
【问题讨论】: