如何在@及之前找到数字(帖子号码);;因为字符串中还有其他数字。最后,它产生了[507,19,1]。
示例:
post507 = "@507::empty in Q1/Q2::can list be empty::yes"
post19 = "@19::Allowable functions::empty?, first, rest::"
post1 = "@1::CS116 W2015::Welcome to first post::Thanks!"
cs116 = [post507, post1, post19]
print (search_piazza(cs116, "l")) =>[507,1,19]
答案 0 :(得分:1)
(?<=@)\d+
使用lookbehind
。请参阅演示。
https://regex101.com/r/eS7gD7/33#python
import re
p = re.compile(r'(?<=@)\d+', re.IGNORECASE | re.MULTILINE)
test_str = "\"@507empty in Q1/Q2can list be emptyyes\"\n \"@19Allowable functionsempty?, first, rest\"\n \"@1CS116 W2015Welcome to first postThanks!"
re.findall(p, test_str)
iF输入位于list
使用
x=["@507;;empty in Q1/Q2;;can list be empty;;yes",
"@19;;Allowable functions;;empty?, first, rest;;",
"@1;;CS116 W2015;;Welcome to first post;;Thanks!"]
print [re.findall(r"(?<=@)\d+",k) for k in x]
答案 1 :(得分:0)
如何在
之前找到字符串中的数字(帖子编号)@
之后和;;
将re.findall
与list_comprehension一起使用。
>>> l = ["@507;;empty in Q1/Q2;;can list be empty;;yes",
"@19;;Allowable functions;;empty?, first, rest;;",
"@1;;CS116 W2015;;Welcome to first post;;Thanks!"]
>>> [j for i in l for j in re.findall(r'@(\d+);;', i)]
['507', '19', '1']
最后将结果数转换为整数。
>>> [int(j) for i in l for j in re.findall(r'@(\d+);;', i)]
[507, 19, 1]
没有正则表达式。
>>> l = ["@507;;empty in Q1/Q2;;can list be empty;;yes",
"@19;;Allowable functions;;empty?, first, rest;;",
"@1;;CS116 W2015;;Welcome to first post;;Thanks!"]
>>> for i in l:
for j in i.split(';;'):
for k in j.split('@'):
if k.isdigit():
print(k)
507
19
1
List_comprehension:
>>> [int(k) for i in l for j in i.split(';;') for k in j.split('@') if k.isdigit()]
[507, 19, 1]