Take the 2-minute tour ×

I'm working on a Python project with user input, and want to reuse specific parts (i.e the part/s that have matched a regular expression) in the output, so a dialog could go something like:

Program: Hello, what have you been doing today? User: I have been foobaring./I went foobaring./(anything else containing 'foobaring') [Where the regular expression is '[a-zA-Z]*ing'] Program: Do you like foobaring?

..but would also have the same result no matter what activity the user entered, so long as it ended in 'ing'.

I currently use variables for the regular expression and the user input like so:

variable = re.compile('regexp')


userinput = raw_input()

so I can use them in an if later on.

TL;DR: Is there anything that returns the string that is the portion of a larger string that matches a regular expression

share|improve this question
add comment

1 Answer

If you surround the regex with parentheses (to make it a group), then you can access that group using match.group(1):

In [89]: import re

In [90]: gerund=re.compile(r'(?u)\b([\w-]+ing)\b')

In [91]: sentence='I went foobaring'

In [92]: match=gerund.search(sentence)

In [93]: match.group(1)
Out[93]: 'foobaring'

Note that using regex to find gerunds is potentially error-prone:

In [103]: sentence='Ming Tsai and I went sight-seeing'

In [104]: match=gerund.search(sentence)

In [105]: match.group(1)
Out[105]: 'Ming'
share|improve this answer
Change \w to \p{L} and you'll have my vote. –  Justin Morgan Mar 15 '11 at 18:59
@Justin E. Morgan: Unfortunately \p{L} is not understood by Python re module. –  unutbu Mar 15 '11 at 19:01
Perhaps [^\W\d_] then? Or just [a-zA-Z]? –  Justin Morgan Mar 15 '11 at 19:02
@Justin E. Morgan: Thanks for pointing out that \w matches digits. [^\W\d_] wouldn't match the hyphen in "sight-seeing", and [a-zA-Z] would miss accented letters. I think it might be better to match too much than too little. Also, I feel silly refining this regex, knowing all the while that "Ming" is not a gerund -- sort of like sharpening an arrow while a tank is bearing down on me. Regex is (ultimately) wrong tool for the battle. –  unutbu Mar 15 '11 at 19:22
I see your point. Didn't consider a hyphen. You're right, using regex to parse natural languages is as perilous as using it on XML. +1 for a good answer. –  Justin Morgan Mar 15 '11 at 19:37
add comment

Your Answer


