Sarp Kaya
Sarp Kaya

Reputation: 3784

Splitting a string by using two substrings in Python

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?

Upvotes: 5

Views: 87

Answers (1)

None
None

Reputation: 2598

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 '

Upvotes: 9

Related Questions