import re
details = '(2,5 cr / K / M)'
m = re.match(r'\((.*?)\w+cr\w/\w(.)\w/\w(.)\)', details)
credit = m.group(0)
state = m.group(1)
grade = m.group(2)
course = {'credit': credit, 'state': state, 'grade': grade}
print course
如该代码片段所示,我想获取(
? cr / ? / ?
),但是它不起作用。 最佳答案
看起来您只是混淆了w和s。可能不适合所有边缘情况:
import re
details = '(2,5 cr / K / M)'
pattern = re.compile(r'^\(([0-9],[0-9]).*/\s([A-Z])\s/\s([A-Z])\)')
m = pattern.match(details)
credit = m.group(1)
state = m.group(2)
grade = m.group(3)
course = {'credit': credit, 'state': state, 'grade': grade}
print course