我尝试使用正则表达式来捕获tweet主体中的所有Twitter句柄。我的挑战是我正试着处理这些问题
例如,对于这些字符串中的每一个,我都用斜体标记了要返回的值。在
"@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
字符,允许使用字符串结尾字符。只返回整个字符串。在
如何编写一个满足这两个条件的表达式?在
似乎您正在尝试匹配以
@
开头的字符串,然后是0+个单词字符,然后是handle
,然后是0+个单词字符。在使用
或者-为了避免在电子邮件中匹配
^{pr2}$@
+个字符:请参见Regex 1 demo和Regex 2 demo(非单词边界要求非单词字符或字符串的开头位于
@
之前)。在注意,
.*
是一个贪婪的点匹配模式,它尽可能多地匹配除换行符以外的任何字符。\w*
只匹配0+个字符(也尽可能多地匹配),但是如果没有使用re.UNICODE
标志(在代码中也没有使用),则从[a-zA-Z0-9_]
集中匹配。在Python demo:
只匹配包含此字符范围的句柄->;
/[a-zA-Z0-9_]/
。在相关问题 更多 >
编程相关推荐