在linux中使用python匹配多行

2024-10-02 08:22:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

谢谢你的回复。你知道吗


Tags: 字符串re内容目标stringislinuxmatch
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:11

在这种情况下,您不需要正则表达式:

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

Output

'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'。你知道吗

相关问题 更多 >

    热门问题