Splitting a string by using two substrings in Python

python, search, string

Solution

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 '

Problem

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?

Original source