我在 Linux 中使用 python 正则表达式时遇到了一个问题。目标字符串具有多行,例如
This is a matched string_1.
This is a matched string_22.
Do not match this line.
我想要做的是匹配“\n\n”之前的所有内容。我用了
deleteString = re.compile('[\s\S]+\n\n')
但它似乎在 Linux 中不起作用。
如何匹配双 \n 之前的字符串。
感谢你的回复。
在这种情况下,您不需要正则表达式:
import re
import sys
text = sys.stdin.read()
# using str.find()
result = text[:text.find('\n\n') + 1]
# using re
result2 = re.match(r'(.*?)$^$', text, flags=re.DOTALL | re.MULTILINE).group(1)
# check that the result is the same
for r in [result, result2]:
print(repr(r))
assert result == result2
'This is a matched string_1.\nThis is a matched string_22.\n'
'This is a matched string_1.\nThis is a matched string_22.\n'
如果您以文本模式从文件中读取输入,那么 Python 会自动将特定于平台的换行符转换为 '\n'。