簡體   English   中英

在linux中使用python匹配多行

[英]Match multi-line using python in linux

我在Linux中使用python regex時遇到了一個問題。 目標字符串有多行,如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM