我的逻辑:ignorecase(IG or I.G. or I.G. or instagram) + (possible space) + (possible :) + (possible space) + (possible @) + (username with - or _ in it) + (end with空格或换行或句号)
首先,关于前缀部分(IG 和 Instagram :)。您可以在 re.compile 函数上使用 re.I 或 re.IGNORECASE 参数来忽略 I.G 和 instagram 上的案例。然后在正则表达式中使用| 或or。
r'(instagram|I\.*G\.*)'
然后转义. 并使用问号? 表示它可以有一个或没有,也可以在可能的空格\s 和可能的冒号: 上。
prefix = re.compile(r'(instagram|I\.*G\.*)\s?:?', re.IGNORECASE)
然后是用户名。首先,在@ 上使用问号? 表示它是可选的。然后两个 (.*) 是用户名的第一个和最后一个(如果有)部分,由破折号或下划线(-|_)? 分隔,这也是可选的。
用户名 = re.compile(r'@?(.)(-|_)?(.)\s?$')
完全放置:
username_regex = re.compile(r'^(instagram|I\.?G\.?)\s?:?\s?(@?.*((-|_).*)?\s?)$', re.IGNORECASE)
我已经对此正则表达式进行了一些测试,这是代码。
import re
username_regex = re.compile(r'^(instagram|I\.?G\.?)\s?:?\s?(@?.*((-|_).*)?\s?)$', re.IGNORECASE)
tests = [
'I.G.: @first-last',
'I.G: @first-last',
'I.g: @first-last',
'I.g.: @first-last',
'i.G: @first-last',
'i.G.: @n-last',
'i.g: @first-last',
'i.g. @first-last',
'I.G.:@first-last',
'I.G@first-last',
'I.g @first-last',
'I.gfirst-last',
'i.G: first_last',
'i.G. first_last',
'ig: first_last',
'i.g. @first-last',
'inStagram: @first-last',
'instAgram: @first-last',
'INSTAGRAM: @first-last',
]
not_matched = 0
for test in tests:
searched = username_regex.search(test)
if searched:
print("MATCH ->", test)
print(searched.group(), '\n\n')
else:
print("========", test)
not_matched += 1
print(not_matched)
# >> 0
如果要获取前缀和用户名,可以使用group()和groups()方法。例如
searched.groups()
# ('I.G:', '@first-last', None, None)
searched.group(0) # 'I.G: @first-last'
# If you want to get the prefix
searched.group(1) # 'I.G:'
# If you want to get the username
searched.group(2) # '@first-last'
注意:我可能在这里的某个地方错了,如果您发现有问题,请告诉我。谢谢。