我正在使用re
搜索一个字符串,这几乎适用于所有情况,除非有换行符(\ n)
例如,如果string定义为:
testStr = " Test to see\n\nThis one print\n "
然后像这样搜索re.search('Test(.*)print', testStr)
并不会返回任何内容。
这是什么问题?我该如何解决?
答案 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 '