Is there a more pythonic way than doing:
parsedStr=origStr[compiledRegex.match(origStr).start():compiledRegex.match(origStr).end())
For exampile assume my original string is "The cat said hi" and my compiled regex is "The.*said" I would pull the text "The cat said"
The above code looks ugly but that's how i've been doing it
3 Answers 3
Use the group method on the match object:
>>> import re
>>> origStr = "The cat said hi"
>>> compiledRegex = re.compile('The.*said')
>>> compiledRegex.match(origStr).group()
'The cat said'
Comments
Does this work for you?
instancesFound = compiledRegex.findall(origStr)
if instancesFound:
parsedStr = parsedParts[0]
Comments
Here's how I'd write it:
search = re.compile(r'^The.*said').search
match = search(input)
if match:
match = match.group(0)
If input is "The cat said my name", match will be "The cat said".
If input is "The cat never mentioned my name", match will be None.
I really like the fact that Python makes it possible to compile a regular expression and assign the particular method of interest to a variable in one line.