通过在Python中使用两个子字符串拆分字符串

时间:2013-11-19 03:26:22

标签: python string search

我正在使用re搜索一个字符串,这几乎适用于所有情况,除非有换行符(\ n)

例如,如果string定义为:

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

然后像这样搜索re.search('Test(.*)print', testStr)并不会返回任何内容。

这是什么问题?我该如何解决?

1 个答案:

答案 0 :(得分:9)

re模块有re.DOTALL表示“。”也应该匹配换行符。一般 ”。”匹配除换行符之外的任何内容。

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

可替换地:

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

示例:

>>> 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 '