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

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

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.

Comments

Your Answer

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.