5

I am searching a string by using re, which works quite right for almost all cases except when there is a newline character(\n)

For instance if string is defined as:

testStr = "    Test to see\n\nThis one print\n "

Then searching like this re.search('Test(.*)print', testStr) does not return anything.

What is the problem here? How can I fix it?

1 Answer 1

9

The re module has re.DOTALL to indicate "." should also match newlines. Normally "." matches anything except a newline.

re.search('Test(.*)print', testStr, re.DOTALL)

Alternatively:

re.search('Test((?:.|\n)*)print', testStr)
# (?:…) is a non-matching group to apply *

Example:

>>> testStr = "    Test to see\n\nThis one print\n "
>>> m = re.search('Test(.*)print', testStr, re.DOTALL)
>>> print m
<_sre.SRE_Match object at 0x1706300>
>>> m.group(1)
' to see\n\nThis one '
2
  • 2
    I suppose not, although if it serves as a reminder to always try your code at the console first even if it costs you a few minutes, it has its value..
    – DSM
    Commented Nov 19, 2013 at 3:46
  • 1
    DSM: If it has value, why did you delete it? :P
    – None
    Commented Nov 19, 2013 at 3:57

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.