0

I am using regex to find time in a string:

re.match('.*(\d{2}-\d{2} \d{2}:\d{2})', "09-22 13:27")

anyway, this is ok, but if \n exists, this return None:

re.match('.*(\d{2}-\d{2} \d{2}:\d{2})', "\n09-22 13:27")

so why .* can not match \n? and how to deal with this?

2
  • See docs.python.org/2/library/re.html#re.DOTALL "why .* can not match \n" - because it's not supposed to. Commented Sep 29, 2015 at 11:29
  • Anyway, . matches any symbol but a newline. Use re.S flag to match a newline with . Commented Sep 29, 2015 at 11:30

3 Answers 3

4

why .* can not match \n? and how to deal with this?

re documentation says:

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

You should note that . matches any symbol but a newline. Use re.S (re.DOTALL) flag to match a newline with .:

import re
obj = re.match('.*(\d{2}-\d{2} \d{2}:\d{2})', "\n09-22 13:27", re.S)
if obj:
    print(obj.group(1))

See IDEONE demo

Sign up to request clarification or add additional context in comments.

3 Comments

in case I'am using re.sub, I tried adding the flag but didn't work. Ended up with a clumsy solution re.finall + replace. Is there a better way?
@juanIsaza Do you mean you are using something like re.sub('(.*)\d{2}-\d{2} \d{2}:\d{2}', r"\g<1>09-22 13:27", flags=re.S)?
sorry, was missing the flags argument.
1

You can exclude newline by using (?

st =  "\n\n09-22 13:27\n"
import re
mo = re.findall(r'(?<!\S)\d{2}-\d{2}\D+\d{2}:\d{2}(?!\S)',st)
print(mo)

Results in:

['09-22 13:27']

Comments

0
print re.match('.*(\d{2}-\d{2} \d{2}:\d{2})', "\n09-22 13:27".strip())

                                                              ^^^^^^^^

You can simply strip the newline.

2 Comments

What if the string necessarily contains new lines? For example, if it's read from a text file and for some reason you don't want to modify it at all when matching? What if your regex pattern depends on new line characters?
by default . matches any character (except for line terminators)

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.