1

I have a string msg like this

msg = "abc 123 \n  456"

I want to do something like this

m = re.match('abc (.*)',msg)

and have m.groups return "123 \n 456"

but currently it only returns "123 "

How would i capture the rest of the string rather than just until the end of the line

2 Answers 2

2

Use the s ( dotall ) modifier forcing the dot to match all characters, including line breaks.

>>> import re
>>> msg = "abc 123 \n  456"
>>> m = re.match(r'(?s)abc (.*)', msg)
>>> m.group(1)
'123 \n  456'
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use the re.DOTALL flag, otherwise the . regular expression atom will not match newlines.

re.DOTALL: Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

So this should do what you want:

m = re.match('abc (.*)', msg, re.DOTALL)

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.