简体   繁体   中英

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?

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 '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM