python中匹配Twitter句柄的正则表达式

2024-10-08 21:18:59 发布

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

我尝试使用正则表达式来捕获tweet主体中的所有Twitter句柄。我的挑战是我正试着处理这些问题

  1. 包含特定字符串
  2. 长度未知
  3. 后面可能是
    • 标点符号
    • 空白
    • 或者是绳子的末端。在

例如,对于这些字符串中的每一个,我都用斜体标记了要返回的值。在

"@handle what is your problem?" [RETURN '@handle']

"what is your problem @handle?" [RETURN '@handle']

"@123handle what is your problem @handle123?" [RETURN '@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字符,允许使用字符串结尾字符。只返回整个字符串。在

^{pr2}$

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

我看过一个coupleother的地方,但还是卡住了。在


Tags: 字符串reyourreturnistwitter字符句柄
2条回答

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

使用

r'@\w*handle\w*'

或者-为了避免在电子邮件中匹配@+个字符:

^{pr2}$

请参见Regex 1 demoRegex 2 demo(非单词边界要求非单词字符或字符串的开头位于@之前)。在

注意,.*是一个贪婪的点匹配模式,它尽可能多地匹配除换行符以外的任何字符。\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']

只匹配包含此字符范围的句柄->;/[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']

相关问题 更多 >

    热门问题