这里是新程序员。 我正在尝试从字符串中获取所有主题标签和链接。正则表达式单独返回期望的结果;但是,将它们合并时将返回一个空列表。如何解决这个问题?
import re
tweet = ('New PyBites article: Module of the Week - Requests-cache '
'for Repeated API Calls - http://pybit.es/requests-cache.html '
'#python #APIs')
# Get all hashtags and links from tweet
def get_hashtags_and_links(tweet=tweet):
tweet_regex = re.compile(r'''(
\(#\w+\)
\(https://[^\s]+\)
)''', re.VERBOSE)
tweet_object = tweet_regex.findall(tweet)
print(tweet_object)
get_hashtags_and_links()
答案 0 :(得分:2)
您正在寻找#\w+
(用括号括起来),紧随其后的是https://[^\s]+
(也用括号括起来),在文本中没有出现
代替使用|
或栏
re.compile(r'''(
\(#\w+\)|
\(https://[^\s]+\)
)''', re.VERBOSE)
但正如指出的\(
所寻找的是实际的括号(未分组)
所以您可能只想
"(#\w+)|(https?://[^\s]+)"
如果需要,您也可以使用非捕获组((?:...)
)
"((?:#\w+)|(?:https?://[^\s]+))"
答案 1 :(得分:0)
您可以按以下方式使用正则表达式:
Try
Cursor = Cursors.WaitCursor
Dim id As Integer = 1
Dim Report1 As New PrintStockReport
Dim dt As DataTable = New DBConnect().selectdata( _
"SELECT StockTable.StockRef, StockTable.StockCat FROM StockTable;")
Report1.SetDataSource(dt)
CrystalReportViewer1.ReportSource = Report1
Cursor = Cursors.Default
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
#[A-Za-z0-9] + ---将搜索#hashtag,后跟任意数字或字母
(\ w +:// \ S +)---这将在推文上搜索路径
答案 2 :(得分:0)
无论您想使用正则表达式进行什么搜索,都需要确保转义#
字符,这对于使用re.X
/ re.VERBOSE
flag编译正则表达式是很特殊的。此选项启用正则表达式模式中的评论,该规则以未转义的哈希符号开始,一直持续到行尾。
当一行包含
#
不在字符类中并且不在 前面加一个未转义的反斜杠,所有字符都位于最左边 这样的#
到行尾都会被忽略。
因此,假设您想匹配#标签或特定的URL,则可以使用
tweet_regex = re.compile(r'''
\#\w+ # Hashtag pattern
| # or
https?://\S+ # URLs
''', re.VERBOSE)
请参见Python code demo,输出:
['http://pybit.es/requests-cache.html', '#python', '#APIs']