2014-07-18 71 views

回答

1
In [3]: department, students = re.search(r"(?:The\s+)?([A-Z]\w*).*\s+(\d+)\s+", line).groups() 

In [4]: print department, students 
Biology 32 
+0

我如何可以結合所有成一條線? – user3852341

+0

@ user3852341,我已經更新了答案。那是你想要的嗎? –

2

多一點明確的方法比基督教的回答,用lookahead

>>> s = "The Biology department averages 32 students/class" 
>>> dept = r'\s+(\w+)\s+(?=department)' 
>>> students = r'\s+(\d+)\s+(?=students)' 
>>> re.findall(dept, s),re.findall(students,s) 
(['Biology'], ['32']) 
1

有點更清晰的方法,LOL

# encoding: UTF-8 
import re 
s = 'The Biology department averages 32 students/class' 
pattern1 = re.compile(r'.*?The (.*?) department') 
match1 = pattern1.match(s) 
if match1: 
    print match1.group(1) 
pattern2 = re.compile(r'.*? (\d.?) students') 
match2 = pattern2.match(s) 
if match2: 
    print match2.group(1) 
相關問題