Skip to content

Use Python regular expression to extract special strings

An answer to this question on Stack Overflow.

Question

Given strings like:

str = '12-1 abcd fadf adfad'

I want to get 12-1. How can you do it in python?

I'm using the following code, but does not work.

m = re.search('.*(\number+-\number+).*', str)
if m:
    found = m.group(0)
    print found

Answer

Try:

import re
str = '12-1 abcd fadf adfad'
m   = re.search('(\d+-\d+)', str)
if m:
    found = m.group(0)
    print found