Categories
Uncategorized

Using regex search and grouping – Python

For some silly reason we have a string with the following information

Jose Christian, tel: 07429225555, id: JC020479

We can use the regular expressions module to find and group the relevant information…just like this.

from re import search

str_line = "Jose Christian, tel: 07429225555, id: JC020479"

# the brackets are the ones that determine the groups
sre_results = search('^(.*), tel: (\d+), id: (.*)$',str_line)

# each bracket will have its own group
str_name = sre_results.group(1)
str_phone = sre_results.group(2)
str_id = sre_results.group(3)

str_output = 'Hello, my names is %s (%s), you can contact me at %s.'

print str_output % (str_name, str_id, str_phone)

That should output

Hello, my names is Jose Christian (JC020479), you can contact me at 07429225555.

The regex broken down

This gives us the name

^(.*), tel:

# make a group which includes
# everything between the start '^'
# and the ', tel:'

This gives us the telephone number

tel: (\d+), id:

# make a second group with all the digits
# that are in between 'tel: ' and ', id:'

Finally, this will give us the id

id: (.*)$

# make a third group containing everything
# between 'id: ' and the end of the line '$'

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s