开发者

Re-using part of user input string that has matched a regular expression

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')

and

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


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜