user3852341
user3852341

Reputation: 1

How do I capture specific words in a string?

I want to capture only the names of the various departments and the numbers of students in:

line = "The Biology department averages 32 students/class" 

I've tried re.search(r"\s\D+\d", line) but it doesn't work.

Upvotes: 0

Views: 77

Answers (3)

Cristian Ciupitu
Cristian Ciupitu

Reputation: 20870

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

In [4]: print department, students
Biology 32

Upvotes: 1

an unique monkey
an unique monkey

Reputation: 341

A bit more clearer method,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)

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

A bit more explicit approach than Christian's answer, using 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'])

Upvotes: 2

Related Questions