【问题标题】:Regular expressions in python to match Twitter handlespython中的正则表达式匹配Twitter句柄
【发布时间】:2016-12-16 02:46:15
【问题描述】:

我正在尝试使用正则表达式来捕获推文正文中的所有 Twitter 句柄。挑战在于我正在尝试处理这些

  1. 包含特定字符串
  2. 长度未知
  3. 之后可以是
    • 标点符号
    • 空格
    • 或字符串的结尾。

例如,对于这些字符串中的每一个,我已用斜体字标记了我想要返回的内容。

“@handle 你有什么问题?” [RETURN '@handle']

“你有什么问题@handle?” [RETURN '@handle']

“@123handle 你有什么问题@handle123?” [返回 '@123handle', '@handle123']

这是我目前所拥有的:

>>> import re
>>> re.findall(r'(@.*handle.*?)\W','hi @123handle, hello @handle123')
['@123handle']
# This misses the handles that are followed by end-of-string

我尝试修改以包含一个允许字符串结尾字符的or 字符。相反,它只返回整个字符串。

>>> re.findall(r'(@.*handle.*?)(?=\W|$)','hi @123handle, hello @handle123')
['@123handle, hello @handle123']
# This looks like it is too greedy and ends up returning too much

如何编写同时满足这两个条件的表达式?

我查看了 couple other 的地方,但仍然卡住了。

【问题讨论】:

  • 您不应该在@handle 之间添加.*。使用\w*。喜欢r'@\w*handle\w*'

标签: python regex twitter


【解决方案1】:

您似乎正在尝试匹配以 @ 开头的字符串,然后是 0+ 个单词字符,然后是 handle,然后又是 0+ 个单词字符。

使用

r'@\w*handle\w*'

或 - 避免匹配电子邮件中的 @+word 字符:

r'\B@\w*handle\w*'

请参阅Regex 1 demoRegex 2 demo\B 非单词边界要求非单词字符或字符串开头位于 @ 之前)。

请注意,.* 是一个贪婪的点匹配模式,它尽可能多地匹配除换行符以外的任何字符。 \w* 仅匹配 0+ 个字符(也尽可能多),但如果未使用 re.UNICODE 标志(并且未在您的代码中使用),则从 [a-zA-Z0-9_] 集合中匹配。

Python demo:

import re
p = re.compile(r'@\w*handle\w*')
test_str = "@handle what is your problem?\nwhat is your problem @handle?\n@123handle what is your problem @handle123?\n"
print(p.findall(test_str))
# => ['@handle', '@handle', '@123handle', '@handle123']

【讨论】:

    【解决方案2】:

    仅匹配包含此字符范围的句柄 -> /[a-zA-Z0-9_]/

    s = "@123handle what is your problem @handle123?"
    print re.findall(r'\B(@[\w\d_]+)', s)
    >>> ['@123handle', '@handle123']
    s = '@The quick brown fox@jumped over the LAAZY @_dog.'
    >>> ['@The', '@_dog']
    

    【讨论】:

    • 这也会从"Some@email.com"中提取@
    • 现在更新我的帖子。
    猜你喜欢
    • 2021-06-08
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多