0

Given:

lst = ['(abc): my name is ?123']

I'm trying to return everything from ': ' till the end of lst[0], for that I tried a regex expression:

    result = re.search(r': (.*?)', lst[0]).group(1)

It returns an empty string. How can this be done using regex correctly? Expected output :

'my name is ?123'

Resources used : Regex wiki

1
  • Remove the ? from r': (.*?)'. It makes your regex stop after the first matching character. Commented Jun 3, 2020 at 7:15

1 Answer 1

3

The issue is that you made your .* lazy by placing ? at the end. Lazy means match as little as possible, for a valid match. In this case, since your pattern does not have anything to match beyond the (.*?), the regex engine is matching empty string. Just use (.*), the non lazy version, and it will work.

lst = ['(abc): my name is ?123']
result = re.search(r': (.*)', lst[0]).group(1)
print(result)

This prints:

my name is ?123
Sign up to request clarification or add additional context in comments.

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.