0

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

asked Oct 22, 2011 at 1:34

3 Answers 3

1

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'
answered Oct 22, 2011 at 1:55
Sign up to request clarification or add additional context in comments.

Comments

0

Does this work for you?

instancesFound = compiledRegex.findall(origStr)
if instancesFound:
 parsedStr = parsedParts[0]
answered Oct 22, 2011 at 1:51

Comments

0

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.

answered Oct 22, 2011 at 5:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.